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

时间:2017-11-13 17:59:09

标签: php mysql laravel laravel-5 collections

我有一系列产品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

如何获得与数组相同的顺序?

2 个答案:

答案 0 :(得分:8)

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

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

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

答案 1 :(得分:1)

这是另一种方法。

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