rameezmeans
rameezmeans

Reputation: 850

Laravel - Eloquent Model Relationship with Order By Inner query is not working

here is my collection.

0 => array:11 [
"_id" => "5d6447ae1ab38901a80c7062"

"order" => 4 //order of out array

"widget_order" => array:6 [
  "_id" => "5d6451281ab38901b4689d24"
  "widget_id" => "5d6447ae1ab38901a80c7062"
  "order" => 3 //order of inner array 
  "user_id" => "5cc211d488737704e876d892"

]
 ]
 1 => array:11 [
"_id" => "5d6447c81ab389ff5c5c37a2"

"order" => 3 //order of out array

"widget_order" => array:6 [
  "_id" => "5d6451281ab38901b4689d25"
  "widget_id" => "5d6447c81ab389ff5c5c37a2"
  "order" => 4 //order of inner array
  "user_id" => "5cc211d488737704e876d892"

]
]

now this is the result of this query.

$allWidgets = Widget::with(['widgetOrder'])->orderBy('order', 'desc')->get();

now i want to sort this on the bases of widget_order.order

i am trying this but its not working.

$allWidgets = Widget::with(['widgetOrder' => function ($query) {
        $query->orderBy('widget_order.order', 'desc');
    }])->get();

Upvotes: 0

Views: 49

Answers (1)

Nico Audy
Nico Audy

Reputation: 89

You can try using this

 $allWidgets = Widget::with('widgetOrder')->orderBy('widgetOrder.order', 'desc')->get();

Upvotes: 1

Related Questions