How do I query a deep relationship in laravel and filter parents by children?
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();