【问题标题】:How to get Records order by dynamic array of values?如何通过动态值数组获取记录顺序?
【发布时间】:2021-11-08 18:36:15
【问题描述】:

我需要获取 Records 以便一组 id 出现在集合的顶部。

$ids = [15, 20];

我试过了:

 $list =  $list->orderByRaw("field(id,".implode(',',$id).")"); 

但这仅适用于 whereIn :

$list =  $list->whereIn('id',$ids)->orderByRaw("field(id,".implode(',',$id).")"); 

但我需要获取除顶部的 ID 15 和 20 之外的所有记录。如何做到这一点。

【问题讨论】:

    标签: mysql laravel eloquent laravel-8 laravel-query-builder


    【解决方案1】:

    这里需要使用MySQL派生表和union

    注意:当你在订单中使用 union 时,你必须设置一个限制,否则它将不起作用。

    $ids = [15, 20];
    DB::table(function($query) use ($ids) {
      $query->from('users')
        ->whereIn('id',$ids)
        ->orderByRaw("field(id,".implode(',',$ids).")")
        ->limit(count($ids))
        ->union(DB::table('users')->whereNotIn('id',$ids));
    },'users1')
    

    您的查询:

    select * from (
          (select * from `users` where `id` in (?, ?) order by field(id,15,20) limit 2)
        union 
          (select * from `users` where `id` not in (?, ?))
      ) as `users1`
    

    【讨论】:

    • 不错的答案。我最好在这里使用完全原始的查询而不是查询生成器。因为构建器没有帮助,反而增加了更多的复杂性。
    【解决方案2】:

    您最好在 PHP 中手动完成此任务,而不是在 MySQL 中。

    $keyed_list = $list->keyBy('id');
    $ordered_list = collect();
    
    foreach ($ids as $id) {
        $ordered_list[] = $keyed_list[$id];
    }
    
    //Add the rest of items
    $ordered_list = $ordered_list->merge($keyed_list->except($ids));
    

    【讨论】:

    • 感谢您的宝贵时间! :)
    【解决方案3】:

    检查这个答案https://stackoverflow.com/a/38574861/11219477

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

    【讨论】:

    • 感谢您的回答。感谢您的时间。但就我而言,我需要在获取数据之前执行此操作。我也在使用 take(10)。所以 10 条记录可能有也可能没有那个 id。
    猜你喜欢
    • 2015-11-20
    • 2021-10-27
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 2022-01-09
    • 2019-11-01
    相关资源
    最近更新 更多