How to request deep relationships in laravel and filter parents by children?

For example, if there are many products in a category that have many skus, how can I get all products that have sku with a price greater than 10?

This returns all categories, but has only the expected skus, where I want only the categories that skus said.

$category = new Category();
$category->with(array('products', 'products.skus' => function ($query) {
    $query->where('price', '>', 10);
}))->get();
+5
source share
2 answers

What you are looking for is this whereHas(). You can also write with(array('products.skus'))directly withoutproducts

$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, withand whereHas, but you can simplify the code a bit by placing 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();
+5
source

For Laravel 5 try this

$category = Category::with(['products','products.skus'])->whereHas('products.skus', function($query) {
    $query->where('price', '>', 10);
})->get();
0
source

All Articles