【问题标题】:Laravel 5.2 Get records the same ordering as in whereIn()Laravel 5.2 获取与 whereIn() 相同排序的记录
【发布时间】:2016-04-16 12:51:09
【问题描述】:

我有这个带有记录 ID 的数组:

$record_ids = [60, 66, 70, 64, 69, 67, 65, 57];

我通过使用模型来获取行,如下所示:

$result = Model::whereIn('id', $record_ids)->get();

问题 - 我想获得与 $record_ids 数组中相同的行顺序。 Laravel 按 ID 升序返回这些行,如下所示:

[57, 60, 64, 65, 66, 67, 69, 70]

如何做到这一点?如何使 Laravel “默认不按 ID ASC 订购”?谢谢。

【问题讨论】:

    标签: php laravel eloquent laravel-5.2


    【解决方案1】:

    你可以像 as 一样使用orderByRaw()

    $result = Model::whereIn('id', $record_ids)
              ->orderByRaw("field(id,".implode(',',$record_ids).")")
              ->get();
    

    【讨论】:

      【解决方案2】:

      使用集合中的sortBy方法,可以按id数组排序。

      $theIds = [2,76,423];
      
      $collection = $collection->sortby(function($model) use ($theIds){
         return array_search($model->id, $theIds);
      });
      

      最好对 $record_ids 进行切片,这将充当偏移量和限制,然后在运行查询后对返回的集合进行排序。

      【讨论】:

        猜你喜欢
        • 2014-11-28
        • 1970-01-01
        • 2019-02-24
        • 2022-01-12
        • 2016-06-19
        • 1970-01-01
        • 1970-01-01
        • 2016-05-16
        • 2017-06-01
        相关资源
        最近更新 更多