How adding brackets in laravel query?

2019-05-09 18:09发布

问题:

My query laravel is like this :

$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();

If I print regular query use this :

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

The result :

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

I would like to add brackets so the query becomes like this :

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

How to add brackets in laravel query?

Thank you

回答1:

It's easy, just pass your query as a closure

       $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();