2017-01-12 35 views
0

所以這裏S中的查詢我想分組的多個對,其中/其特徵在於,條件一起

$products = Product::whereHas('ProductFilter' , function($q) use ($filter_groups){ 

      foreach($filter_groups as $k=>$v) 
      $q->where('f_id' , $k)->whereIn('value' ,$v); 

     })->get(); 

,這將導致在這個查詢

select * from `products` where exists 

( 
    select * from `product_filters` where 
`product_filters`.`product_id` = `products`.`id` and 
`f_id` = '4' and `value` in ('10', '11', '12', '13') and 
`f_id` = '10' and `value` in ('34') 

) 

我想組這些線thoghether

`f_id` = '4' and `value` in ('10', '11', '12', '13') 
    and 
`f_id` = '10' and `value` in ('34') 

like

(`f_id` = '4' and `value` in ('10', '11', '12', '13') ) 
and 
    (`f_id` = '10' and `value` in ('34')) 

回答

1

你可以將你在那裏築巢where()方法調用的條款讓你的例子將是這個樣子:

$products = Product::whereHas('ProductFilter' , function($q) use ($filter_groups){ 
    foreach($filter_groups as $k=>$v) { 
     $q->where(function (Builder $query) { 
      $query->where('f_id', $k); 
      $query->whereIn('value' ,$v); 
     }); 
    })->get(); 

Here是文檔的相關章節。

+0

thanx,很好的工作'Builder $ query'應該只是'$ query' – hretic

+0

給予'where()'方法的回調函數將被賦予一個查詢構建器的實例。在你的情況下,它會'\ Illuminate \ Database \ Eloquent \ Builder'。如果查詢沒有雄辯,它將是'Illuminate \ Database \ Query \ Builder'。 – nCrazed

相關問題