You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何用whereIn按数组元素顺序返回查询结果?

按传入数组顺序返回ORM查询结果的实现方法

数据库默认不会按照whereIn的参数数组顺序返回结果,需要手动指定排序逻辑,下面提供几种适配不同场景的ORM实现方式:

方法一:适配MySQL数据库

利用MySQL的FIELD()函数,通过ORM的orderByRaw方法指定排序规则:

$products = [350, 410, 362, 256, 193];
$searchResults = ProductSearch::whereIn('product_id', $products)
    ->orderByRaw('FIELD(product_id, ?)', [$products])
    ->get();

FIELD()函数会根据传入的product_id数组顺序对结果排序,第一个参数是要排序的字段,后续参数为目标顺序的数组。

方法二:适配PostgreSQL数据库

PostgreSQL可以借助array_position()函数实现:

$products = [350, 410, 362, 256, 193];
$searchResults = ProductSearch::whereIn('product_id', $products)
    ->orderByRaw('array_position(?, product_id)', [$products])
    ->get();

方法三:查询后通过集合排序(跨数据库通用)

如果不想依赖数据库特定函数,可先查询结果,再通过Laravel集合的sortBy方法按原数组顺序重排:

$products = [350, 410, 362, 256, 193];
$searchResults = ProductSearch::whereIn('product_id', $products)->get();

// 按原数组顺序排序
$sortedResults = $searchResults->sortBy(function ($item) use ($products) {
    return array_search($item->product_id, $products);
});

// 转为连续索引的集合(可选)
$sortedResults = $sortedResults->values();

这种方法不依赖数据库特性,适配多数据库环境,但数据量较大时,性能略逊于数据库层面排序。

内容的提问来源于stack exchange,提问作者Sagar Gautam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:06:24