【问题标题】:Laravel whereIn incorrect order of resultLaravel whereIn 结果顺序不正确
【发布时间】:2020-01-05 11:30:58
【问题描述】:

当 id 数组与客户表中的 id 匹配时,我想从数据库中获取记录。

这是我的 ID 数组:

0 => 1
1 => 1788
2 => 887
3 => 697
4 => 719

我有以下查询,

$customers = Customer::whereIn('id', $idArray)->get();

我得到了我需要的所有客户,但顺序不正确。我正在按以下顺序吸引客户。

1
697
719
887
1788

这是默认行为还是我做错了什么。

感谢任何建议。

【问题讨论】:

标签: php laravel eloquent where-clause


【解决方案1】:

使用ò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"
    }
]

【讨论】:

    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 2013-08-09
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2017-05-29
    • 1970-01-01
    相关资源
    最近更新 更多