Laravel 5.1: Eloquent relationship hasMany, Limit records
Hi all,
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 return 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 advice?
Any comments are highly appreciated.
@tronghiep92 There isn't an easy way to do this. @JarekTkaczyk posted a solution a while ago though. Try it out because it's exactly what you're looking for.
@tronghiep92 the link pasted by thomas is showing how to do that in MySQL. However, your approach is right as well, just mind that you cannot directly assign relation:
// instead of this:
$feed->comments = $feed->comments->take(5);
// do this:
$feed->setRelation('comments', $feed->comments->take(5));
@JarekTkaczyk just found your article and was about to post it here :)
Anyways, why can't he directly set the relation? Does laravel use a magic method in order to fetch the relations? If so, why won't it use a magic method to set it?
@itzursai can we use paginate function after that?is there any way to put paginate(10) on the result?something like that.
public function searchQuery(Request $request) {
$params = [
'page' => 1,
'perPage' => 50,
'sortField' => 'created_at',
'sortOrder' => 'desc',
];
$requestParams = $request->query();
$params = array_merge($params, $requestParams);
I had same problem, trying to get 2 trips for each company.
I am using Laravel 5.6 and I'm not sure if I should posted on here. But this was the first result it came up when i search for a solution.
I found a way, works for me, in L5.6.
public function getFeed($user_id)
{
return Feed::whereUserId($user_id)->take(10)->get()->each(function($feed) {
$feed->load('feed_comments');
});
}
model:
public function comments() {
return $this->hasMany(Comment::class);
}
public function feed_comments() {
return $this->comments()->take(2);
}