如何在laravel查询中添加括号?

时间:2016-01-04 10:26:02

标签: laravel laravel-5

我的查询laravel是这样的:

$customer = Customer::where('full_name', 'iLIKE', '%'.$param['keyword'].'%')
                                ->orWhere('mobile', 'iLIKE', '%'.$param['keyword'].'%')
                                ->orWhere('phone', 'iLIKE', '%'.$param['keyword'].'%')
                                ->where('published','1')
                                ->where('customer_status','N')
                                ->orderBy('full_name', 'ASC')->get();

如果我打印常规查询,请使用:

DB::listen(function($sql, $bindings, $time) {
            \Log::info($sql);
            \Log::info(print_r($bindings,1));
            \Log::info($time);
        });

结果:

select * from "ss_customer" 
where "full_name" iLIKE '%ronaldo%' or "mobile" iLIKE '%ronaldo%' or "phone" iLIKE '%ronaldo%' and "published" = 1 and "customer_status" = 'N' 
order by "full_name" asc

我想添加括号,以便查询变为如下:

select * from "ss_customer" 
where ("full_name" iLIKE '%ronaldo%' or "mobile" iLIKE '%ronaldo%' or "phone" iLIKE '%ronaldo%') and "published" = 1 and "customer_status" = 'N' 
order by "full_name" asc

如何在laravel查询中添加括号?

谢谢

1 个答案:

答案 0 :(得分:3)

这很简单,只需将您的查询作为闭包传递

       $customer = Customer::where(function($query) use ($param) {
        $query->where('full_name', 'iLIKE', '%'.$param['keyword'].'%')
                ->orWhere('mobile', 'iLIKE', '%'.$param['keyword'].'%')
                ->orWhere('phone', 'iLIKE', '%'.$param['keyword'].'%');
    })->where('published','1')
        ->where('customer_status','N')
        ->orderBy('full_name', 'ASC')->get();