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?
One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)
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.
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.
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.
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();
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