Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting relationships in Laravel

I have a model Post which has a hasMany('Comments') relationship. I would like to fetch all Posts with the Comments relationship, but only the latest one comment for each Post. And because there are thousands of posts with thousands of comments each, an option such as this is not possible due to performance issues (i.e. loading all comments for each post and then doing $post->comments[0]->value):

Post::with('comments' => function($query){
    $query->orderBy('created_at','desc')
});

Nor can I do:

Post::with('comments' => function($query){
    $query->orderBy('created_at','desc')->limit(1)
});

as this just doesn't work.

I am completely sure I'm not the only one with this issue and I did manage to find some 'attempts for a solution' but not a stable example of working code. Can anyone help please?

like image 978
Yasen Slavov Avatar asked Sep 23 '14 20:09

Yasen Slavov


People also ask

How many types of relationships are there in laravel?

One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)

Has many with limit in laravel?

Laravel Limit result from hasMany relation. has relation with category and product. But you want to limit the product data. For limit result from hasMany relation in laravel you can use setRelation function. This function generating a collection of array.

What is many to many relationship in laravel?

In the category_product table, you can see product_id 1 have multiple entiries with category_id 2 and 3. That's how you can create many to many relationships in Laravel Eloquent. Obviously, you can use the inverse of this relationship to attach a category to multiple products.

What is morph relationship in laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.


1 Answers

try this one: lets say you have defined the "comments" relation on your Post model. this is how you can take all the comments belong to that:

App\Post::all()->comments()->orderBy('comments.created_at')->take(1)->get();
like image 69
Salar Avatar answered Oct 19 '22 07:10

Salar