Php laravel中的急负荷关系及其条件

Php laravel中的急负荷关系及其条件,php,laravel,eloquent,Php,Laravel,Eloquent,我在树中有相互关联的类别。每个类别都有许多子类。每个终端类别都有许多产品 产品也属于多种不同类型 我想用他们的孩子和产品来加载这些类别,但我还想设置一个条件,即产品是某种类型的 这就是我的分类模型的样子 public function children() { return $this->hasMany('Category', 'parent_id', 'id'); } public function products() { return $this->hasM

我在树中有相互关联的类别。每个类别
都有许多子类。每个终端类别
都有许多产品

产品也属于多种不同类型

我想用他们的孩子和产品来加载这些类别,但我还想设置一个条件,即产品是某种类型的

这就是我的分类模型的样子

public function children()
{
    return $this->hasMany('Category', 'parent_id', 'id');
}


public function products()
{
    return $this->hasMany('Product', 'category_id', 'id');
}
产品模型

public function types()
{
    return $this->belongsToMany(type::class, 'product_type');
}
在我的数据库中,我有四个表: 类别、产品、类型和产品类型

我尝试过像这样快速加载,但它加载所有产品,而不仅仅是满足条件的产品:

$parentLineCategories = ProductCategory::with('children')->with(['products'=> function ($query) {
        $query->join('product_type', 'product_type.product_id', '=', 'product.id')
            ->where('product_type.type_id', '=', $SpecificID);
    }]])->get();

如果符合您的需要,请尝试使用当前查询,而不是当前查询。 (我用你的评论修改了我的回答如下)

您可以根据关系的存在来限制结果,如下所示:

ProductCategory::with('children')
            ->with(['products' => function ($q) use($SpecificID) {
                $q->whereHas('types', function($q) use($SpecificID) {
                    $q->where('types.id', $SpecificID)
                });
            }])
            ->get();

这仍然为我提供了所有产品。您正在寻找的
产品
儿童
或家长
类别
相关,请检查是否存在数据问题。i、 e所有
产品
属于同一
父类别
我正在寻找与子类别相关的产品。我得到的分类和他们的孩子分类都很好。问题在于我希望基于约束加载的产品(它们属于我指定的类型)。到目前为止,我得到的所有产品的儿童类别。我想过滤那个结果。这有用吗?
ProductCategory::with('children')
            ->with(['products' => function ($q) use($SpecificID) {
                $q->whereHas('types', function($q) use($SpecificID) {
                    $q->where('types.id', $SpecificID)
                });
            }])
            ->get();