hasMany
The hasMany association creates a one-to-many relationship where one instance of the source model has many instances of the target model.
Basic Example
(tableName: 'users')
class User {
()
()
DataType id = DataType.INTEGER;
(Post, foreignKey: 'userId', as: 'posts')
List<Post>? posts;
static UserModel get model => UserModel();
}
(tableName: 'posts')
class Post {
()
()
DataType id = DataType.INTEGER;
('user_id')
DataType userId = DataType.INTEGER;
DataType title = DataType.STRING;
static PostModel get model => PostModel();
}
Usage
// Find user with all their posts
final user = await User.model.findOne(
where: User.model.id.equals(1),
include: (u) => [
u.posts(),
],
);
print('User ID: ${user?.id}');
print('Posts: ${user?.posts?.length}');
for (final post in user?.posts ?? []) {
print(' - ${post.title}');
}