withRelation method
Requests eager loading for the relation named name.
Eager loading fetches related models in the same query or a minimal number of subsequent queries, preventing N+1 query problems.
name is the name of the relation as defined in the model.
constraint is an optional callback to apply additional WHERE conditions
to the eager-loaded relation.
Example:
// Eager load the 'posts' relation for each user
final usersWithPosts = await context.query<User>()
.withRelation('posts')
.get();
// Eager load 'posts' and filter them
final usersWithPublishedPosts = await context.query<User>()
.withRelation('posts', (query) => query.where('isPublished', true))
.get();
Implementation
Query<T> withRelation(
String name, [
PredicateCallback<OrmEntity>? constraint,
]) {
final path = _resolveRelationPath(name);
return _copyWith(
relations: _mergeRelationLoad(_relations, path, constraint),
);
}