简体   繁体   中英

Laravel grouping where clauses in Eloquent

I have created Eloquent query in laravel 5.4 in which I want to filter data through 6 different combination which are as follows:

  1. Category
  2. Subcategory
  3. industry
  4. style
  5. orientation
  6. color

This is the query I have used

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

Its working fine except one thing that category and subcategory is ignored when I fetch results from different category and subcategory I want data where category and subcategory should always match and other 4 remaining filter can be optional.

You need to group as optional conditions:

$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);

Try your query in following way:

$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);

it will always match for category && subcategory And other fields are optional.

Hope this will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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