laravel - 关系数据中的 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);
}
}
解决方案
从 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();
推荐阅读
- python - 计算每个单词出现的不同行数
- php - AWS 弹性 beantalk 上安装了哪些默认 php 扩展?
- javascript - 如何解决 ajax django 中的 JSONdecode 错误?
- c# - Unity - 使用按钮的 onClick 功能切换场景
- python - 有没有办法让 Eclipse(使用 pydev)在每个类或 def 语句的开头插入一个空的文档字符串?
- r - R中的Write.table循环
- ibm-watson - IBM Watson Visual Recognition:在端点 (...) 的 guid (...) 的 getAllCollections 响应中收到 403 中的无效状态
- maven - 在哪里可以找到 GCP 云构建者的列表?
- excel - (excel VBA):将记录集的剩余行复制到第二张表
- python - 为什么所有标签_都是-1?由 DBSCAN 在 Python 中生成