我的产品是这个代码。我用with()方法加载变量关系。 我有一些过滤器。但如果不存在任何变化,我会得到产品。
如何才能获得存在差异的产品?
$query = Product::with(array(
'variations' => function($query) use($filters){
if(isset($filters['price_start']) && !empty($filters['price_start'])){
$query->groupBy('id')->having(DB::raw('SUM(price_base + price_engraving)'), '>=', $filters['price_start']);
}
if(isset($filters['price_end']) && !empty($filters['price_end'])){
$query->groupBy('id')->having(DB::raw('SUM(price_base + price_engraving)'), '<=', $filters['price_end']);
}
if(isset($filters['q_magazine_start']) && !empty($filters['q_magazine_start'])){
$query->where('q_magazine', '>', $filters['q_magazine_start']);
}
if(isset($filters['q_magazine_end']) && !empty($filters['q_magazine_end'])){
$query->where('q_magazine', '<', $filters['q_magazine_end']);
}
return $query;
}
))->whereIn('id', $productList);
答案 0 :(得分:1)
要做到这一点,你必须再次使用whereHas
做同样的事情。由于闭包将完全相同,我们可以将其放在变量中以避免重复代码:
$filterClosure = function($query) use ($filters){
if(isset($filters['price_start']) && !empty($filters['price_start'])){
$query->groupBy('id')->having(DB::raw('SUM(price_base + price_engraving)'), '>=', $filters['price_start']);
}
if(isset($filters['price_end']) && !empty($filters['price_end'])){
$query->groupBy('id')->having(DB::raw('SUM(price_base + price_engraving)'), '<=', $filters['price_end']);
}
if(isset($filters['q_magazine_start']) && !empty($filters['q_magazine_start'])){
$query->where('q_magazine', '>', $filters['q_magazine_start']);
}
if(isset($filters['q_magazine_end']) && !empty($filters['q_magazine_end'])){
$query->where('q_magazine', '<', $filters['q_magazine_end']);
}
};
$query = Product::with(array('variations' => $filterClosure))
->whereHas('variations', $filterClosure)
->whereIn('id', $productList);
(顺便说一句,没有必要在匿名函数的末尾返回$query
)
我们发现您需要将groupBy
语句更改为where
$filterClosure = function($query) use ($filters){
if(isset($filters['price_start']) && !empty($filters['price_start'])){
$query->where(DB::raw('price_base + price_engraving'), '>=', $filters['price_start']);
}
if(isset($filters['price_end']) && !empty($filters['price_end'])){
$query->where(DB::raw('price_base + price_engraving'), '<=', $filters['price_end']);
}
// same code as above
};