php – 如何在laravel中查询深层关系并由子级过滤父级?

例如,如果某个类别包含许多具有多个skus的产品,那么如何获得价格大于10的所有产品?

这将返回所有类别,但只附加了预期的skus,其中我只想要具有所述skus的类别.

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

解决方法:

您正在寻找的是WhereHas().您也可以直接使用(array(‘products.skus’))编写产品

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

你需要both,with和whereHas,但你可以通过将闭包放在变量中来简化代码

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

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...