Laravel route model binding with sorted eager loading? #34057
Unanswered
FrazeColder
asked this question in
General
Replies: 2 comments
-
Whether or not this is a solution for you, in general you can set relations with |
Beta Was this translation helpful? Give feedback.
0 replies
-
So, if I got you right I sort my
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have products which have also comments. This comments can be voted and comments can also have child comments. The comments get loaded via eager loading
$with
which is defined in theproduct
model and the child comments get as well loaded via eager loading which is also defined in thecomments
model. The child comments can also be voted (but don't have any child comments).Product.php (Model)
Comment.php (Model)
I use route model binding to receive my product in the
ProductController.
Here is an example of the routeRoute::get('/product/{product}', ['as' => 'product.show', 'uses' => 'ProductController@show']);
and the functionshow
:ProductController@show:
In the
show
function I can now access thecomments
of the product, as well as thechild comments
of thecomments
and all the other relations which get loaded via the$with
attribute in the models.Now comes questions. As I already have loaded the relationship, how can I either 1. sort them now or 2. pass the sort arguments to the model to get a sorted relationship back?
When I write
dd($product->comments->sortByDesc('created_at')->toArray());
I get myproduct
with thecomments
which are sorted bycreated_at
. That's what I want. But I cannot assign the sorted collection to theproduct
collection like this$product->comments = $product->comments->sortByDesc('created_at');
because$product->comments
is@property-read
.I also don't want to do another query and pass this
$product->comments()>orderBy('created_at', 'desc')->get();
to my response. Because then the eager loading in the model redundant.Is there a way to 1. either sort the relationship collection or 2. pass the sort arguments to the model to get a sorted relationship back?
I actually want to stick to my route binding model. I know I could pass the sorting arguments and product
id
as arguments and then execute it viaget
. But is there a solution to do that within the model eager loading?Also, please note I want to sort my comments also by likes and the count of child comments they have. I don't want to sort them only by date, so I need to pass the sort argument to the model when choosing a solution for number 2.
Kind regards!
Beta Was this translation helpful? Give feedback.
All reactions