我在laravel 5.4中创建了Eloquent查询,其中我想通过6种不同的组合过滤数据,如下所示:
这是我使用的查询
$updatedproducts = Product::Where('category', $cat)
->Where('subcategory', $subcat)
->whereIn('industry', $industrytags)
->orWhereIn('style', $styletags)
->orWhereIn('orientation', $orientationtags)
->orWhereIn('color', $colortags)
->paginate(12);
它的工作正常,但是当我从不同的类别和子类别中获取结果时忽略了类别和子类别的一件事我希望数据类别和子类别应该始终匹配,而其他4个剩余的过滤器可以是可选的。
答案 0 :(得分:1)
您需要将其分组为可选条件:
$updatedproducts = Product::Where('category', $cat)
->Where('subcategory', $subcat)
->where(function ($where) use ($industrytags, $styletags, $orientationtags, $colortags) {
$where->whereIn('industry', $industrytags)
->orWhereIn('style', $styletags)
->orWhereIn('orientation', $orientationtags)
->orWhereIn('color', $colortags);
})
->paginate(12);
答案 1 :(得分:0)
按以下方式尝试查询:
$updatedproducts = Product::Where('category', $cat)
->Where('subcategory', $subcat)
->where(function($q) use($industrytags ,$styletags, $orientationtags,$colortags) {
$q->whereIn('industry', $industrytags)
->orWhereIn('style', $styletags)
->orWhereIn('orientation', $orientationtags)
->orWhereIn('color', $colortags);
})
->paginate(12);
它始终匹配category
&& subcategory
其他字段是可选的。
希望这会有所帮助