Hello Artisans π
Did you know you can get relationship counts even after retrieving the parent model? π€
Using the loadCount method, you may load a relationship count after the parent model has already been retrieved:
$book = Book::first();
$book->loadCount('genres');
If you need to set additional query constraints on the count query, you may pass an array keyed by the relationships you wish to count. The array values should be closures which receive the query builder instance:
$book->loadCount(['reviews' => function (Builder $query) {
$query->where('rating', 5);
}])
Top comments (0)