4
votes

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

1
Does this answer your question? Laravel eager load function limitHafez Divandari

1 Answers

0
votes

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.