Php 我如何查询拉威尔的深厚关系并按子女筛选父母?

Php 我如何查询拉威尔的深厚关系并按子女筛选父母?,php,laravel,eloquent,Php,Laravel,Eloquent,例如,如果一个类别有许多产品,其中有许多sku,我如何获得所有sku价格大于10的产品 这将返回所有类别,但仅附加了预期的SKU,其中我只希望包含上述SKU的类别 $category = new Category(); $category->with(array('products', 'products.skus' => function ($query) { $query->where('price', '>', 10); }))->get(); 您要

例如,如果一个类别有许多产品,其中有许多sku,我如何获得所有sku价格大于10的产品

这将返回所有类别,但仅附加了预期的SKU,其中我只希望包含上述SKU的类别

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

您要查找的是
whereHas()
。您还可以使用(数组('products.sku')直接编写
,而不使用
产品

$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();
您既需要带
,也需要带
和where has
,但您可以通过将闭包放入变量中来简化代码:

$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();

我不断得到
调用undefined method illumb\Database\Query\Builder::products.skus()
您有最新版本的Laravel吗?最近才启用了对
中的嵌套关系的支持。运行
composer-udpate
好的,我仍然使用4.1,希望升级不会破坏一切。