如何查询 laravel 中的深层关系并通过 children 过滤 parents?

How do I query a deep relationship in laravel and filter parents by children?

例如,如果一个类别有很多产品,每个产品都有很多 SKU,我如何获得所有具有价格大于 10 的 SKU 的产品?

这 returns 所有类别,但只附加了预期的 skus,我只想要带有 skus 的类别。

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

您要找的是whereHas()。你也可以直接写 with(array('products.skus')) 而不用 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();

withwhereHas 两者都需要,但您可以通过将闭包放在变量中来稍微简化代码:

$priceGreaterTen = function($query){
    $query->where('price', '>', 10);
};

$category = new Category();
$categories = $category->with(array('products', 'products.skus' => $priceGreaterTen))
                       ->whereHas('products.skus', $priceGreaterTen)
                       ->get();

对于 Laravel 5,试试这个

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