【问题标题】:Conditional orderBy有条件的orderBy
【发布时间】:2016-04-02 14:45:03
【问题描述】:

我正在一个项目中构建一个过滤器功能。

我有一个过滤选项“显示最新”、“显示最旧”和许多其他选项。我找到了一种如何实现条件 where 子句的方法,但似乎没有条件 orderBy 类。

我的条件 where 子句如下所示:

$query->where(function($query) use ($request){
   if( ! empty($request->input('prices')) ){
      $opts = $request->prices;
      $query->where('price_id', $opts[0]);
   }
})

有没有办法用 ->orderBy 来做到这一点?

更新

return Auction::where('end_date', '>', Carbon::now() )
         ->where('locale', $locale)
         ->where('sold', 0)
         ->where(function($query) use ($request){

             if( ! empty($request->input('prices')) ){
                  $opts = $request->prices;
                  $query->where('price_id', $opts[0]);
             }
         })->paginate(8);

我怎样才能以雄辩的方式做到这一点?

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-query-builder


    【解决方案1】:

    当然,你可以这样做:

    if ($request->input('id_desc')) {
       $query = $query->orderBy('id', 'DESC');
    }
    

    或者你可以这样做:

    $columns = ['id','name',]; // here define columns you allow for sorting
    $orderBy = ['ASC', DESC'];
    
    
    $column = $request->input('order_by_column');
    $type = $request->input('order_by_type');
    
    if (!in_array($column, $columns)) {
      $column = 'id';
    }
    if (!in_array($type , $orderBy )) {
      $type = 'ASC';
    }
    
    $query = $query->orderBy($column, $type);
    

    编辑

    使用您的代码:

    $query = Auction::where('end_date', '>', Carbon::now() )
             ->where('locale', $locale)
             ->where('sold', 0)
             ->where(function($query) use ($request){
    
                 if( ! empty($request->input('prices')) ){
                      $opts = $request->prices;
                      $query->where('price_id', $opts[0]);
                 }
             });
    
    
    if ($request->input('id_desc')) {
        $query = $query->orderBy('id', 'DESC');
    }
    
    return $query->paginate(8);
    

    【讨论】:

    • @RW24 请看新答案
    • 谢谢,这正是我所需要的。现在看起来很合乎逻辑!这是过滤器功能的好习惯吗?还是应该换一种方式?
    • 这很好,但正如我所展示的,您可能应该创建某种“白名单”,并允许用户仅按这些字段过滤,以防在输入中发送字段名称
    猜你喜欢
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多