例如,如果某个类别包含许多具有多个skus的产品,那么如何获得价格大于10的所有产品?
这将返回所有类别,但只附加了预期的skus,其中我只想要具有所述skus的类别.
$category = new Category();
$category->with(array('products', 'products.skus' => function ($query) {
$query->where('price', '>', 10);
}))->get();
解决方法:
您正在寻找的是WhereHas().您也可以直接使用(array(‘products.skus’))编写产品
$category = new Category();
$categories = $category->with(array('products', 'products.skus' => function ($query) {
$query->where('price', '>', 10);
}))
->whereHas('products.skus', function($query){
$query->where('price', '>', 10);
})->get();
你需要both,with和whereHas,但你可以通过将闭包放在变量中来简化代码:
$priceGreaterTen = function($query){
$query->where('price', '>', 10);
};
$category = new Category();
$categories = $category->with(array('products', 'products.skus' => $priceGreaterTen))
->whereHas('products.skus', $priceGreaterTen)
->get();