HasMany
A "one-to-many" relationship is another essential type of database association. Let's illustrate this with an example where we have a User model associated with a Post model. To establish this connection, we define a method called posts within the User model. This posts method invokes the HasMany method and returns its output, representing that a user can have multiple posts in the database. This relationship allows us to easily retrieve all the posts associated with a specific user when needed.
Usage
$getRelation
User? user = await User().find(1);
await user?.$getRelation('blogs')
List<Blog> blogs = user?.blogs;
Info
When eager is true the $getRelation do not need to call.
preload
Info
When eager is true the preload do not need to call.
related
User? user = await User().find(1);
List<Blog> activeBlogs = await user?.related<Blog>('blog')?.where('status', 'active').get();
Options
model
foreignKey
localKey
onQuery
@DoxModel()
class User extends UserGenerator {
@HasMany(Post)
Post? posts;
@HasMany(Post, onQuery: activePostQuery)
Post? activePosts;
static QueryBuilder<Post> activePostQuery(Post q) {
return q.where('status', 'active');
}
}
Info
onQuery method must be a static method inside the model.