HasManyThrough关系是否可能比两个层次更深? [英] Is it possible to have a HasManyThrough relationship that's deeper than two levels?

查看:109
本文介绍了HasManyThrough关系是否可能比两个层次更深?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

Product
BaseProduct
BaseCode
Series

每个都是单独的实体,但它们相关。

Each of them is something of a separate entity, but they're related.

产品有一个外键 BaseProduct BaseProduct 有一个外键 BaseCode BaseCode 有一个外键系列

Product has a foreign key to BaseProduct, BaseProduct has a foreign key to BaseCode and BaseCode has a foreign key to Series.

我已经在我的 BaseCode 模型中指定了一个方法,所以我可以选择与该特定 BaseCode 相关的所有产品

I have specified a method within my BaseCode model so I can select all of the Products that are related to that particular BaseCode:

public function Products()
{
    return $this->hasManyThrough('Product', 'BaseProduct', 'BaseCodeId', 'BaseProductId');
}

BaseCodeId 是对于 BaseCode 的PK和 BaseProduct 中指向该PK的FK,而 BaseProductId BaseProduct 的PK,而在 Product 表中,有一个FK指向

BaseCodeId is the PK for the BaseCode and the FK in BaseProduct that is pointing to that PK, and BaseProductId is the PK for BaseProduct, and in the Product table, there's a FK that points to it.

这一切都很好,而且对我来说只是dandy。

This is all well and good, and works just dandy for me.

我会喜欢去一级,并在我的系列模型中定义如下:

I'd like to go one level further though, and define something like the following in my Series model:

public function Products()
{
    //It's here that I'd have no idea what to do - is there something like a three-level deep "hasManyThroughThrough" or something?
    return $this->BaseProducts()-> /* and then whatever I'd do here to get the products */
}

public function BaseProducts()
{
    return $this->hasManyThrough('BaseProduct', 'BaseCode', 'SeriesId', 'BaseCodeId');
}

如何获取所有 code>与系列相关联的code>

How do I get all of the Products associated with Series like that?

推荐答案

我有点新到4.1,但它看起来好像 hasManyThrough()不是为您正在寻找的关系类型而设计的,而是真正只是两层深度的快捷方式渴望加载。

I am somewhat new to 4.1, but it looks as though hasManyThrough() was not designed for the types of relationships you are looking for and is really just a shortcut for two level deep eager loading.

尝试传统的渴望加载...

Try traditional eager loading instead...

$ data =产品:: with('BaseProduct.BaseCode.Series');

您将需要确保在模型中设置关系必要的而不是调用模型名称,您将需要调用定义关系的方法。

You will need to make sure the relationships are setup in your models as necessary and instead of calling model names, you will want to call the methods that are defining the relationships.

显然,请确保您的模型知道主键是什么使用 protected $ primaryKey ='SeriesID'等...

Also obviously, be sure your models know what the primary keys are by using protected $primaryKey = 'SeriesID' etc...

这篇关于HasManyThrough关系是否可能比两个层次更深?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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