Laravel查询生成器-高级条件子句(可选参数) [英] Laravel Query Builder - Advanced Conditional Clauses (optional parameters)

查看:49
本文介绍了Laravel查询生成器-高级条件子句(可选参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要查询生成器的子句接受可选参数.例如,考虑以下内容:

I need clauses with Query Builder that accept optional parameters. For example, consider the following:

我们有三个搜索字段,分别用于产品标题,公司名称和位置(邮政编码,城市或州).2 ^ 3(8)种可能性:

We have three search fields for the product title, company name, and location (postal code, city or state). 2^3 (8) possibilities:

该位置与OR连接.

WHERE location.postal_code LIKE '%...%' OR location.city LIKE '%...%';

搜索框之间的关系

WHERE (location.postal_code LIKE '%...%' OR location.city LIKE '%...%') AND company.name LIKE '%...%';

我们可以使用原始查询和if-else语句来编写它.我们如何使用查询生成器将其写为干净"?

We could write that with a raw query and if-else statements. How can we write that "clean" with the Query Builder?

推荐答案

您应使用where闭包,例如:

You should use where closure like this :

    $q->where(function($q) use($request) {
     if($request->code)
     {
       $q->orWhere('postal_code ','LIKE','%'.$request->code.'%');
     }

     if($request->city)
     {
       $q->orWhere('city','LIKE','%'.$request->code.'%');
     }

     if($request->companyName)
     {
      $q->where('companyName',.....);
     }
})->get();

因此,您可以在何处或何处形成干净的查询.您也可以传递您的请求以在闭包内部使用它.您也可以使用$ q-> orWhere在其中传递函数.

So you have where, orWhere to form your query clean. Also you can pass your request to use it inside closure. Also you can use $q->orWhere to pass function inside it.

这篇关于Laravel查询生成器-高级条件子句(可选参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆