簡體   English   中英

Laravel將Eloquent中的where子句分組

[英]Laravel grouping where clauses in Eloquent

我在laravel 5.4中創建了雄辯的查詢,其中我想通過6種不同的組合來過濾數據,如下所示:

  1. 類別
  2. 子目錄
  3. 行業
  4. 樣式
  5. 取向
  6. 顏色

這是我使用過的查詢

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

它的工作很好,但當我從不同的類別和子類別中獲取結果時,類別和子類別被忽略的一件事我想要的數據,其中類別和子類別應始終匹配,而其余4個過濾器可以是可選的。

您需要將分組作為可選條件:

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

通過以下方式嘗試查詢:

$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匹配,其他字段是可選的。

希望這會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM