Relationship Column Order

I have the following query:

$items = UserItems::with('item') ->where('user_id','=',$this->id) ->where('quantity','>',0) ->get(); 

I need to order it by item.type, so I tried:

 $items = UserItems::with('item') ->where('user_id','=',$this->id) ->where('quantity','>',0) ->orderBy('item.type') ->get(); 

but I get an Unknown column 'item.type' in 'order clause'

What am I missing?

+9
source share
2 answers

join () works great thanks to @rypskar comment

 $items = UserItems ::where('user_id','=',$this->id) ->where('quantity','>',0) ->join('items', 'items.id', '=', 'user_items.item_id') ->orderBy('items.type') ->get(); 
+5
source

Well, your energetic load probably doesn't create the expected request, and you can check it by turning on the query log.

But I would probably just use a collection filter:

 $items = UserItems::where('user_id','=',$this->id) ->where('quantity','>',0) ->get() ->sortBy(function($useritem, $key) { return $useritem->item->type; }); 
+7
source

All Articles