2014-02-06 36 views
4

我有以下型号:是否有可能具有比两个层次更深的HasManyThrough关系?

Product 
BaseProduct 
BaseCode 
Series 

他们每个人都是一个独立的实体的东西,但他们的关系。

Product有一个外键BaseProductBaseProduct有一个外键BaseCodeBaseCode有一个外键Series

我指定我BaseCode模型中的一个方法,所以我可以选择所有相关的特定BaseCodeProducts的:

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

BaseCodeId对于BaseCode的PK和FK在BaseProduct是指向那个PK,BaseProductIdBaseProduct的PK,在Product表中有一个指向它的FK。

这一切都很好,并为我工作只是花花公子。

我想去一个级别上的,虽然,确定像​​我Series模型如下:

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 S的?

回答

6

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

尝试传统的预先加载,而不是...

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

您需要确保关系是建立在你的模型作为必要的,而不是调用模型的名字,你将要调用的方法正在定义关系。

也明显,确保您的机型知道什么是主键是使用protected $primaryKey = 'SeriesID'等等

+1

谢谢你,先生。经过一番沉重的挖掘和混乱之后,我一直无法让雄辩的弯曲我喜欢的方式,并得出了相同的结论。 –

相关问题