I have a problem with Laravel 5.1: Eloquent relationship hasmany, Limit records I have 2 tables: feeds, comments. The request is to obtain 5 feeds and comments accordingly to each particular feed. I am currently using the below query:
public function getFeed($user_id){
return Feed::whereUserId($user_id)->with(['comments'])->take(10)->get()->map(function ($feed) {
$feed->comments = $feed->comments->take(5);
return $feed;
});
}
However, it returns all the comments.
My thinking was that the $feed->comments = $feed->comments->take(5);
line doesn't work. I only want to get 5 comments for each feed, do you have any advise? Any comments are highly appreciated. Thank you!
It's better late than never, I was facing the same issue yesterday and ended up by sets the entire relations array on the model.
So in your case it will be like this:
return Feed::whereUserId($user_id)->take(10)->get()->map(function($feed) {
$feed->setRelation('comments', $feed->comments->take(5));
return $feed;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With