vviglaf's avatar

Eloquent Pagination While Eager Loading

I was just re-watching the eloquent performance patterns series from Laracast.

In this lesson;

we are just eager loading and using setRelation to get

  1. Feature
  2. Feature's comments
  3. comment's user
  4. 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:

  1. How can I paginate the comments without broke this well optimized logic
  2. I need a deep explanation for this lesson, about setRelation and other stuff.

Thanks!

Here are the things I've tried:

  1. Controller

     $comments = $feature->comments()->with('user')->paginate(10);
    
     $comments->getCollection()->each->setRelation('feature', $feature);
    
    
     return view('feature', [
         'feature' => $feature,
         'comments' => $comments,
     ]);
    
  2. Blade @foreach ($feature->comments as $comment) to --> @foreach ($comments as $comment)

result for the content with 46 comment:

Models (64)

  1. App\User - 7
  2. App\Comment - 56
  3. App\Feature - 1

Queries (5)

  1. select * from features where id = '10' limit 1
  2. select count(*) as aggregate from comments where comments.feature_id = 10 and comments.feature_id is not null
  3. select * from comments where comments.feature_id = 10 and comments.feature_id is not null order by created_at asc limit 10 offset 0
  4. select * from users where users.id in (1, 4, 5, 6, 15, 16, 19)
  5. select * from comments where comments.feature_id = 10 and comments.feature_id is not null order by created_at asc

conclusion

first/original logic without pagination has 3 queries and 64 models

0 likes
0 replies

Please or to participate in this conversation.