首页 > 解决方案 > 关系数据中的 Laravel OrderBy

问题描述

如何在输出的关系集合中排序grocery.name?它现在只是按父 ID 作为默认值排序,我对此不感兴趣。

我试图改变这个控制器......

这是它的样子

public function indexalpha()
    {
        $list = DailyList::with('grocery')->where('completed', 0)->get();
        return $list;
    }

这是我的更改,如果我想更改grocery.name 以按字母顺序输出

public function indexalpha()
    {
        $list = DailyList::with(['grocery' => function ($q) {
            $q->orderBy('name', 'desc');
        }])->where('completed', 0)->get();
        return $list;
    }

我的输出看起来像是按 id 排序的

[
{
"id": 554, // this is apparently the default sorting
"grocery_id": 110,
"amount": 1,
"completed": 0,
"created_at": "2020-03-27 08:29:53",
"updated_at": "2020-03-27 08:29:53",
"grocery": {
  "id": 110,
  "name": "Cookie", // Want to order this part!!!
  "measurement": "Stk",
  "created_at": "2020-02-20 12:25:26",
  "updated_at": "2020-02-20 12:25:26"
}
},
{
"id": 555, // this is apparently the default sorting
"grocery_id": 107,
"amount": 1,
"completed": 0,
"created_at": "2020-03-27 08:51:10",
"updated_at": "2020-03-27 08:51:10",
"grocery": {
  "id": 107,
  "name": "Pampers", // Want to order this part!!!
  "measurement": "Stk",
  "created_at": "2020-01-27 13:50:24",
  "updated_at": "2020-01-27 13:50:24"
}
}
]

我的表结构

Groceries
- id
- name
- measurement

模型中的关系

class DailyList extends Model
{


    public function grocery()
    {
        return $this->belongsTo(Grocery::class);
    }
}

标签: laravelsortingcontrollerrelationship

解决方案


从 laravel 6 及更高版本开始,您可以使用更简洁的语法来做到这一点

https://laravel-news.com/eloquent-subquery-enhancements

$list = DailyList::with('grocery')->orderByDesc(
    ProductPrice::select('name')
        ->whereColumn('daily_lists.grocery_id', 'groceries.id')
        ->orderByDesc('name')
        ->limit(1)
)->where('completed', 0)->get();

推荐阅读