是否有可能拥有比两个级别更深的 HasManyThrough 关系?

2023-12-14

我有以下型号:

Product
BaseProduct
BaseCode
Series

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

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

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

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

BaseCodeId是 PKBaseCode和 FK 在BaseProduct指向该 PK,并且BaseProductId是 PKBaseProduct,并且在Product表中,有一个 FK 指向它。

这一切都很好,对我来说非常有用。

不过,我想更进一步,并在我的中定义类似以下内容的内容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');
}

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


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

尝试传统的急切加载...

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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否有可能拥有比两个级别更深的 HasManyThrough 关系? 的相关文章

随机推荐