Laravel分组Eloquent中的条款

时间:2017-09-15 11:05:49

标签: php laravel eloquent

我在laravel 5.4中创建了Eloquent查询,其中我想通过6种不同的组合过滤数据,如下所示:

  1. 类别
  2. 子类别
  3. industry
  4. style
  5. 取向
  6. 颜色
  7. 这是我使用的查询

     $updatedproducts  = Product::Where('category', $cat)
                         ->Where('subcategory', $subcat)
                         ->whereIn('industry', $industrytags)
                         ->orWhereIn('style', $styletags)
                         ->orWhereIn('orientation', $orientationtags)
                         ->orWhereIn('color', $colortags)
                         ->paginate(12);
    

    它的工作正常,但是当我从不同的类别和子类别中获取结果时忽略了类别和子类别的一件事我希望数据类别和子类别应该始终匹配,而其他4个剩余的过滤器可以是可选的。

2 个答案:

答案 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其他字段是可选的。

希望这会有所帮助