Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1: Eloquent relationship hasmany, Limit records

Tags:

laravel-5

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!

like image 480
nghiepit Avatar asked Mar 15 '23 12:03

nghiepit


1 Answers

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;
});
like image 106
Luthfi Avatar answered Apr 01 '23 13:04

Luthfi