简体   繁体   English

如何在 Laravel 中与关系进行排序

[英]how to sort in Laravel with relationship

I want to sort this data by category name.我想按类别名称对这些数据进行排序。 this is my sample table这是我的示例表

enter image description here在此处输入图像描述

this is sample data enter image description here这是示例数据在此处输入图像描述

this is the output and my expected output enter image description here这是 output 和我预期的 output在此处输入图像描述

I played around with this and it seems nested eager loading creates another query using IN .我玩过这个,似乎嵌套的急切加载使用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 .因此, name将引用类别,但它将与 pivot 表以 1:1 的比例匹配,因此此 orderBy 将无用,因为它将使用IN之后的 categoryItems 排序。

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.看来您需要进行连接才能在 pivot 表级别进行排序,类别顺序很重要,但您也不会在该级别获得可用的 category.name。

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:请注意,外部查询也可以使用 orderBy,因此您也可以执行以下操作:

$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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM