Let's say I have 250 users in users table and each user has one or many books, and each book has one or many chapters. Now I would like to print the user names, with their book names.
Controller:
$users = User::all();
in blade:
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>
@foreach($user->books as $book)
{{ $book->name }},
@endforeach
</td>
</tr>
@endforeach
# of queries 252
Now to overcome the n+1 problem, the query should be
$users = User::with('books')->get();
Now the # of queries are only 2.
I want to print the book names with number of chapters like this-> BookName(# of chapters). So in my blade
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>
@foreach($user->books as $book)
{{ $book->name }} ({{ $book->chapters->count() }}),
@endforeach
</td>
</tr>
@endforeach
so for 750 books with 1500 chapters the # of queries are about 752 and it increases if chapter number increases.
Is there any better Eloquent way to reduce it or should I go for raw SQL queries?
withsupports nested relationships. You should be able to usewith('books.chapters')