基于值的多个字段查询(如果不是空的话)包括查询但如果null则从laravel 5中的查询中删除它

时间:2015-04-28 17:21:48

标签: laravel laravel-5

我的表单搜索包含:

customer id     customer name    email    postal 

当用户填写客户名称时,例如" john"并发送电子邮件,例如" hotmail" 我想搜索客户表,其中custumer_name喜欢"%john%"并发送电子邮件,如"%hotmail%"。

但填写customer_name,电子邮件和邮政时

从custumer_name喜欢"%john%"的客户中选择*并发送电子邮件,如"%hotmail%"和邮政= 123

我尝试了什么:

if ($name != "")    Customer::with('province')->with('country')->with('user')->where("customer_name", "like", "%$name%")->get();

if ($name != "" and $email != "")
  Customer::with('province')->with('country')->with('user')->where("customer_name", "like", "%$name%")->where("email", "like", "%$email%")->get();

。 。 。 检查所有情况,但这不是有效的解决方案,因为如果字段增加,我会更多的IF。

什么是最佳解决方案?

1 个答案:

答案 0 :(得分:1)

使用高级人员

if (!empty($customer_id)) {
        $customerCollection = $customerCollection->where("id","like", "%$customer_id%");
     }

     if (!empty($name)) {       
        $customerCollection = $customerCollection->where(function($q) use ($name){$q->where("first_name", "like", "%$name%")
                                                                        ->orWhere("middle_name", "like", "%$name%")
                                                                        ->orWhere("last_name", "like", "%$name%");});
     }
相关问题