laravel when方法如何进行分组

需求
select * from table where a=1 and (b=2 or c=3)

结合实际业务需求($is)及laravel的when方法

$this->where('a',1)
    ->when($is,function($query){
        $query->where('b',2)
              ->orWhere('c',3);
    });

实际产生语句
select * from table where a=1 and b=2 or c=3

没在文档上找到这个问题的解决方案,求解

阅读 6.7k
5 个回答

先还是用原生的whereRaw()方法凑合着用下了

把它抱起来就好啦

$this->where('a',1)
     ->when($is,function($query){
         return $query->where(function($query2){
             $query2->orWhere('a' => b)->orWhere('c' => 'd');
             //$query2->orWhere(['a' => b, 'c' => 'd']);
         });
     });
     
//select * from table where a = 1 and (a = b or c = d)

题主效率有问题.

select * from table where a=1 and b=2
union
select * from table where a=1 and b=3;

参数分组#
DB::table('users')

        ->where('name', '=', 'John')
        ->orWhere(function ($query) {
            $query->where('votes', '>', 100)
                  ->where('title', '<>', 'Admin');
        })
        ->get();
        官方文档上有这种参数分组的处理
        传送门:https://d.laravel-china.org/docs/5.3/queries#parameter-grouping
$this->where('a',1)->where(function($query) use($is){
        if($is)
            $query->where('b',2)->orWhere('c',3);
    });
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题