在Eloquent中按自定义顺序对集合进行排序

时间:2016-11-22 00:23:29

标签: php arrays laravel eloquent

我有一系列ID,如下所示:

$ids = [5,6,0,1]

使用Eloquent我可以使用->whereIn('id', $ids)功能搜索这些ID。正如预期的那样,将按Id的升序返回结果,有没有办法可以返回数组所在顺序的结果?或者,最简单的方法是按照$ids数组的顺序转换集合吗?

3 个答案:

答案 0 :(得分:10)

如果您有特定的订单,那么您需要使用Collection Methods

要按照您指定的特定顺序获取您的ID,您可以使用sortBy方法,如下所示,其中collection是您的模型集合:

$ids = [ 5, 6, 0, 1];

$sorted = $collection->sortBy(function($model) use ($ids) {
    return array_search($model->getKey(), $ids);
});

// [ 5, 6, 0, 1] // (desired order)

要随机化您的收藏,您可以使用shuffle方法。

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] // (generated randomly)

有关更具体的要求,请参阅shuffle和/或sortBy上的Laravel Docs

如果您确实没有特定的订单,则可以在版本5.2及更高版本中使用->inRandomOrder(),旧版本需要使用->orderBy(DB::raw('RAND()'))进行原始查询。

答案 1 :(得分:1)

请参阅MySQL order by field in Eloquent的答案。可以在SQL查询中对数据进行排序。其他答案是建议您按照“错误”的顺序提取数据后对数据进行排序。

您的代码应如下所示:

const obj=[{room:5},{room:35},{room:25},{room:15}];

static test(obj)
  {
    for (let i=0;i<obj.length;i++)
    {
      obj[i].room++;
    }
    return obj;
  }
return {ok:true,D:obj,R:this.test(obj)};

答案 2 :(得分:-1)

您可以将函数传递给sortBy方法以执行复杂排序:

$ids = [5,6,0,1];

$collection = YourModel::whereIn('id', $ids)->sortBy(function($model) use ($ids) {
    // Access your array order here and modify the sorting here
});