Jul 31, 2023
0
Level 3
Eloquent Pagination While Eager Loading
I was just re-watching the eloquent performance patterns series from Laracast.
we are just eager loading and using setRelation to get
- Feature
- Feature's comments
- comment's user
- reducing the query count and model responses on usage of this command @if ($comment->isAuthor())
via:
$feature->load('comments.user');
$feature->comments->each->setRelation('feature', $feature);
return view('feature', ['feature' => $feature]);
I have two question:
- How can I paginate the comments without broke this well optimized logic
- I need a deep explanation for this lesson, about setRelation and other stuff.
Thanks!
Here are the things I've tried:
-
Controller
$comments = $feature->comments()->with('user')->paginate(10); $comments->getCollection()->each->setRelation('feature', $feature); return view('feature', [ 'feature' => $feature, 'comments' => $comments, ]); -
Blade
@foreach ($feature->comments as $comment)to -->@foreach ($comments as $comment)
result for the content with 46 comment:
Models (64)
- App\User - 7
- App\Comment - 56
- App\Feature - 1
Queries (5)
- select * from
featureswhereid= '10' limit 1 - select count(*) as aggregate from
commentswherecomments.feature_id= 10 andcomments.feature_idis not null - select * from
commentswherecomments.feature_id= 10 andcomments.feature_idis not null order bycreated_atasc limit 10 offset 0 - select * from
userswhereusers.idin (1, 4, 5, 6, 15, 16, 19) - select * from
commentswherecomments.feature_id= 10 andcomments.feature_idis not null order bycreated_atasc
conclusion
first/original logic without pagination has 3 queries and 64 models
Please or to participate in this conversation.