how to sort in Laravel with relationship

Viewed 55
1 Answers

I played around with this and it seems nested eager loading creates another query using IN. It isn't a join so you can't reference the previous query. Thus the name would refer to the category but it would be matched up 1:1 with the pivot table and thus this orderBy will be useless since it would use the categoryItems ordering following the IN.

It seems you need to do a join in order to be able to orderBy at the pivot table level where the category order would matter, but you wouldn't have the category.name available at that level either.

Unless of course you had a join.

Thus if you decided to use a join, it would look something like this:

$allItems = Item::with(['categoryItems' => function($q1){
    // Note: Categories here is a reference to the table name not the model.
    $q1->join('Categories','category_id','=','categories.id')
    ->orderBy('name','ASC');
}]);

$allItems = $items->get();

foreach ($allItems as $item) {
    echo $item->name.':<br>';
    foreach($item['categoryItems'] as $cat) {
        echo "- {$cat['name']}<br>";
    }
   echo '<br>';
}

Note that the outer query can also use an orderBy so you can do things like this too:

$items = Item::with(['categoryItems' => function($q1){
    $q1->join('Categories','category_id','=','categories.id')
    ->orderBy('name','DESC'); // name here is the cat name
}])->orderBy('name','DESC'); // name here is the item name
Related