1 回答
TA贡献1780条经验 获得超3个赞
使用òrderByRaw查询构建器方法向查询添加原始“order by”子句。该方法的签名是
$this orderByRaw(string $sql, array $bindings = [])
所以它需要一个原始的 sql 查询作为参数,让我们使用DB 提供所需$ids_ordered 字符串的外观给它一个
$idArray = [
0 => 1,
1 => 1788,
2 => 887,
3 => 697,
4 => 719,
];
$ids_ordered = implode(',', $idArray); // Basically casts the array values to a string
$customers = Customer::whereIn('id', $idArray)
->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))
->get();
return $customers;
原始 sql 查询就像(假设MySQL 为数据库引擎)
select * from `customers` where `id` in (?, ?, ?, ?, ?) order by FIELD(id, 1,1788,887,697,719)
结果:
[
{
"id": 1,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
},
{
"id": 1788,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
},
{
"id": 887,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
},
{
"id": 697,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
},
{
"id": 719,
"created_at": "2019-09-02 12:21:15",
"updated_at": "2019-09-02 12:21:15"
}
]
- 1 回答
- 0 关注
- 106 浏览
添加回答
举报