For example, if a category has many products which has many skus, how do I get all products that have a sku with a price greater than 10?
This returns all the categories but only has the expected skus attached, where I want only the categories that have said skus.
$category = new Category();
$category->with(array('products', 'products.skus' => function ($query) {
$query->where('price', '>', 10);
}))->get();
What you're looking for is whereHas()
. Also you can write with(array('products.skus'))
directly without products
$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();
You need both, with
and whereHas
but you can simplify the code a bit by putting the closure in a variable:
$priceGreaterTen = function($query){
$query->where('price', '>', 10);
};
$category = new Category();
$categories = $category->with(array('products', 'products.skus' => $priceGreaterTen))
->whereHas('products.skus', $priceGreaterTen)
->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With