简体   繁体   English

laravel 中的急切加载关系,并带有关系条件

[英]Eager load relationships in laravel with conditions on the relation

I have categories related to each other in a tree.我在树中有相互关联的类别。 Each category hasMany children.每个类别hasMany孩子。 Each end category hasMany products.每个类目hasMany产品。

The products also belongsToMany different types.产品还belongsToMany多种不同类型。

I want to eager load the categories with their children and with the products but I also want to put a condition that the products are of a certain type.我想用他们的孩子和产品急切地加载类别,但我也想设置一个条件,即产品属于某种类型。

This is how my categories Model looks like这是我的类别模型的样子

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


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

The Product Model产品型号

public function types()
{
    return $this->belongsToMany(type::class, 'product_type');
}

In my database I have four tables: category, product, type, and product_type在我的数据库中,我有四个表:category、product、type 和 product_type

I've tried eager loading like so but it loads all the products and not just the ones that fulfil the condition:我试过像这样急切加载,但它加载了所有产品,而不仅仅是满足条件的产品:

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

Instead of the current query, try if this fits your needs.而不是当前查询,请尝试这是否符合您的需要。 (I modified my answer as follows with your comment) (我根据您的评论修改了我的答案如下)

$parentLineCategories = ProductCategory::with([
            'children' => function ($child) use ($SpecificID) {
                return $child->with([
                    'products' => function ($product) use ($SpecificID) {
                        return $product->with([
                            'types' => function ($type) use ($SpecificID) {
                                return $type->where('id', $SpecificID);
                            }
                        ]);
                    }
                ]);
            }
        ])->get();

You can use whereHas to limit your results based on the existence of a relationship as:您可以使用whereHas根据关系的存在来限制您的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM