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

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

问题描述

我有以下型号:

Product
BaseProduct
BaseCode
Series

它们中的每一个都是一个独立的实体,但它们是相关的.

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

Product 有一个 BaseProduct 的外键,BaseProduct 有一个 BaseCode 的外键BaseCode 有一个 Series 的外键.

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

我在我的 BaseCode 模型中指定了一个方法,因此我可以选择与该特定 BaseCode 相关的所有 Products:

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

BaseCodeIdBaseCode 的 PK 和 BaseProduct 中指向该 PK 的 FK,以及 BaseProductIdBaseProduct 的 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.

这一切都很好,对我来说很花哨.

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

不过,我想更进一步,并在我的 Series 模型中定义类似以下内容:

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

我如何像这样获得与 Series 相关联的所有 Product?

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

推荐答案

我对 4.1 有点陌生,但看起来 hasManyThrough() 不是为您正在寻找的关系类型而设计的for and 实际上只是两级深度预加载的快捷方式.

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 = Product::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天全站免登陆