php - Laravel whereIn 结果顺序不正确
问题描述
当 id 数组与客户表中的 id 匹配时,我想从数据库中获取记录。
这是我的 ID 数组:
0 => 1
1 => 1788
2 => 887
3 => 697
4 => 719
我有以下查询,
$customers = Customer::whereIn('id', $idArray)->get();
我得到了我需要的所有客户,但顺序不正确。我正在按以下顺序吸引客户。
1
697
719
887
1788
是默认行为还是我做错了什么。
任何建议表示赞赏。
解决方案
使用ò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"
}
]