4

I have a Post and Comment model.

Post has a hasMany relationship to Comment. Comment has a belongsTo relationship to Post.

I want to eager load posts with their comments, but I want to limit to only get 3 comments per posts. How can I do this by Eloquent?

Post::with(array('comments' => function($query)
{
  $query->take(3);
}))->take(10)->get();

But this constraint will only load 3 comments for all the 10 posts instead of 3 comments per post.

If this is not yet possible via Eloquent, is there any other solution that also implements eager loading?

Thanks

Henson
  • 5,563
  • 12
  • 46
  • 60
  • Does this answer your question? [Laravel eager load function limit](https://stackoverflow.com/questions/41664645/laravel-eager-load-function-limit) – Hafez Divandari Dec 01 '20 at 11:40

1 Answers1

0

This is not a laravel limitation but a SQL limitation.

Best option is to not use eager loading and cache the results for performance instead.

hannesvdvreken
  • 4,858
  • 1
  • 15
  • 17
  • So the optimal way for this is to do a nested query (loop each post, get comments for each post) and cache the results? – Henson Feb 26 '14 at 16:56
  • There are 3 ways: The first way is to loop each post and get the limited comments array per post and cache each limited array. This way, you have the problem n+1 requests to the database. In the case N is large, this can take a long time. The second way is get all comments. Then cap the number of comments in php. This can possibly be memory intensive. The slightly more difficult way is to store an array of comment identifiers into every post row. This requires an additional read request and possibly an additional write request to your sql database on every new comment. – hannesvdvreken Mar 10 '14 at 10:55
  • Have you looked into window functions? Not sure if your database supports them (e.g. mysql) but if so they can be very good at rolling up data like this – mils Mar 27 '17 at 04:27