Home > front end >  Nested Eager Loading count
Nested Eager Loading count

Time:04-29

I need to get the contacts count of each author

$books = Book::with('author.contacts')->get();

The following attempt doesn't work

$books = Book::with('author.contacts')
             ->whithCount('author.contacts')
             ->get();

CodePudding user response:

You can try something like this, where you use a function to get the count.

Book::with(['author' => function($query){
   $query->withCount('contacts');
}])->get();

You can access likes count by author->contracts_count;

  • Related