laravel中的热负荷关系以及该关系上的条件 [英] Eager load relationships in laravel with conditions on the relation

查看:44
本文介绍了laravel中的热负荷关系以及该关系上的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在树中有彼此相关的类别.每个类别都有 hasMany 个子级.每个最终类别 hasMany 产品.

I have categories related to each other in a tree. Each category hasMany children. Each end category hasMany products.

产品还属于Tolongy 不同类型.

我希望向他们的孩子和产品加载类别,但是我还想提出一个条件,即产品属于某种类型.

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');
}

产品型号

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

在我的数据库中,我有四个表:类别,产品,类型和product_type

In my database I have four tables: category, product, type, and 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();

这篇关于laravel中的热负荷关系以及该关系上的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆