【问题标题】:what is the equivelent orderby case query in laravel?laravel 中的等价 orderby 案例查询是什么?
【发布时间】:2017-05-03 08:53:35
【问题描述】:

Laravel 5.4 中与此等价的查询是什么

select id,name
from friends
order by case when id in (5,15,25) then -1 else id end,id

【问题讨论】:

    标签: laravel


    【解决方案1】:
    //Controller namespace
    use DB;
    use App\Friend;
    
    //In controller method    
    $friends = Friend::select('id', 'name')
                   ->orderBy(DB::raw('case when id in (5,15,25) then -1 else id end,id'))
                   ->get();
    

    【讨论】:

      【解决方案2】:

      您可以使用 raw() 进行原始 SQL 查询,而不是使用 Eloquent 的查询构建器。 Here is the documentation for it.

      如果有帮助,here 是 Laravel 4 中提出的类似问题;旧但仍然相关。

      希望对你有帮助!

      【讨论】:

        【解决方案3】:

        有多种方法可以实现这一点。

        如果你想使用 Laravel 查询生成器:

        $result = DB::select('
            select id, name
            from friends
            order by case when id in (5,15,25) then -1 else id end, id
        ');
        

        如果你想使用 Laravel Eloquent,结合 Query Builder:

        $result = \App\Friend::select('id', 'name')
                    ->orderBy(DB::raw('case when id in (5,15,25) then -1 else id end'), 'id')->get();
        

        【讨论】:

          【解决方案4】:

          您可以传递查询的raw 部分,而不是像那样构建整个事情。这样做:

          DB::table('your_table')
              ->orderBy(
                  DB::raw('case when id in (5,15,25) then -1 else id end,id')
              )->get()
          

          将首先返回 id 为 5,15 和 25(如果存在)的记录,然后返回按 id 排序的其余记录。不知道是不是你想要的。

          【讨论】:

            猜你喜欢
            • 2018-07-03
            • 1970-01-01
            • 2021-08-04
            • 1970-01-01
            • 2017-10-10
            • 2012-09-28
            • 2012-10-29
            • 2018-12-17
            • 2020-07-24
            相关资源
            最近更新 更多