0

I want to load all my news with comments. Right now, I am retrieving all news with all comments. However, I only want 2 comments to be shown to each news item.

$news = News::with('user')->with('comments.user')->orderBy('created_at', 'desc')->get();

How do I get only 2 comments out with each news item?

Patrick Reck
  • 11,246
  • 11
  • 53
  • 86

1 Answers1

1

I'm not sure if that's possible.

You can do something like this:

News::with(array('comments.user' => function($q) { $q->take(2); }));

But it will take two comments from the entire set (genereated query will look like SELECT * FROM users WHERE id IN (...) LIMIT 2).

I had the same problem. I've done it in a dirty way - iterate over News records, fetch to them two comments and cache the whole thing.

radmen
  • 1,584
  • 9
  • 13