繁体   English   中英

Laravel:如何使用whereIn方法获得自定义排序的eloquent集合

[英]Laravel: How to get custom sorted eloquent collection using whereIn method

我有一系列产品ID,我需要检索模型集合。 数组是这样的:

$ids = array(9, 2, 16, 11, 8, 1, 18);

现在,我正在使用以下代码行来获取集合。

$products = Product::whereIn('id', $ids)->get();

但它根据他们的ID对产品进行了分类。 例如: 1, 2, 8, 9, 11, 16, 18 我需要的是相同的顺序中$ids阵列即9, 2, 16, 11, 8, 1, 18

我该怎么做以获得与数组中相同的顺序?

使用mysql的Field()函数(如果你使用的是mysql数据库)和DB::raw()的laravel一样

$products = Product::whereIn('id', $ids)
    ->orderBy(DB::raw("FIELD(id,".join(',',$ids).")"))
    ->get();

Field()返回逗号分隔列表的索引位置

这是另一种方法。

$ids = array(9, 2, 16, 11, 8, 1, 18);
$products = User::whereIn('id', $ids)->orderByRaw('FIELD(id, '.implode(',', $ids).')')->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM