简体   繁体   English

有条件地将where子句添加到雄辩的查询中

[英]Conditionally add where clause to eloquent query

I have a products database. 我有一个产品数据库。 I allow users to enter a search term and I display products related to their search term. 我允许用户输入搜索词,并显示与他们的搜索词相关的产品。 I'm wanting to add the ability for the user to further filter these results by "gender" using AJAX. 我想为用户增加使用AJAX通过“性别”进一步过滤这些结果的功能。 If the user selects a gender from a select box this is sent to the URL query string. 如果用户从选择框中选择性别,则将其发送到URL查询字符串。

here is my code responsible for detecting if "gender" is in the query string. 这是我的代码,负责检测查询字符串中是否包含“性别”。

$searchTerm = request('s');
$gender = request('gender');

$productsQuery = DB::table('products')
                ->where('title', 'LIKE', "%$searchTerm%");
if ($gender != "") {
    $productsQuery->where('gender', '=', "%$gender%");
}

$productsQuery->get(); 

When this method is called. 调用此方法时。 I receive an empty collection. 我收到一个空集合。

Your idea and approach is correct, but you are mixing LIKE and = queries. 您的想法和方法是正确的,但您正在混合使用LIKE=查询。 % is a wildcard, but that can be only be used with LIKE . %是通配符,但是只能与LIKE一起使用。

So, if you want to use a wildcard and LIKE , 因此,如果您想使用通配符和LIKE

if(!empty($gender)) {
    $productsQuery->where('gender', 'LIKE', "%$gender%");
}

Or if you want to match by exact text, 或者,如果您想按确切的文字进行匹配,

if(!empty($gender)) {
    $productsQuery->where('gender', $gender);
}

Your current code will search for the exact match of the literal string %male% , for example. 例如,您当前的代码将搜索文字字符串%male%的完全匹配项。

Keep in mind that by using a wildcard, male will also match female (as they both contain the word "male"). 请记住,通过使用通配符, male也将与female匹配(因为它们都包含“男性”一词)。

You should use LIKE also in the second where clause: 您还应该在第二个where子句中使用LIKE:

$productsQuery->where('gender', 'LIKE', "%{$gender%}");

EDITED 已编辑

If you need to search for the exact gender you must not use wildcards at all. 如果您需要搜索确切的性别,则完全不能使用通配符。

$productsQuery->where('gender', '=', $gender);

Actually you can do this in one query. 实际上,您可以在一个查询中执行此操作。 Just like that: 就像这样:

$productsQuery = DB::table('products')
->where('title', 'LIKE', '%'.$searchTerm.'%')
->where(function($query) use ($gender){
     if($gender != ""){
        $query->where('gender', '=', $gender);
      }
})
->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM