当 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"
}
]
关于php - Laravel where结果顺序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57756755/