withCount abstract method

QueryBuilderInterface<T> withCount(
  1. dynamic relations
)

Load relationship counts without loading the full relationships.

Adds a {relation}Count attribute to each model with the count.

final users = await User.query()
  .withCount(['posts', 'comments'])
  .get();

print(users.first.postsCount); // 25
print(users.first.commentsCount); // 150

You can also apply constraints to the count:

final users = await User.query()
  .withCount({
    'posts': (q) => q.where('published', '=', true),
    'comments': (q) => q.where('approved', '=', true),
  })
  .get();

Implementation

QueryBuilderInterface<T> withCount(dynamic relations);