php - Laravel where结果顺序不正确

标签 php laravel eloquent where-clause

当 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/

相关文章:

php - 如何在php中匹配两行mysql同一个表

PHP exec使用ffmpeg转换目录中的所有文件

javascript - jQuery 更改表单的响应文本

php - vs 代码 - 引号内的 php intellisense

php - 如何使用laravel动态显示从数据库获取的文本框值

mysql - 让 Laravel 在插入/更新时使用 MySQL 默认值

php - 使用 Laravel 5 热切加载多个索引关系

php - 无法加载和使用 Imagick(DLL 错误)(Windows 8)

php - 使用 Laravel 将 youtube-dl 输出流式传输到 S3

php - Laravel Eloquent : How to select not attached records in many to many relationship?