将多对where / where条件组合在一起

时间:2017-01-12 18:07:50

标签: php laravel eloquent laravel-5.2

所以这里是我想要的查询

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

)

我想将这些行分组为

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

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

1 个答案:

答案 0 :(得分:1)

您可以通过嵌套where()方法调用对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是文档的相关部分。