2014-02-06 38 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

謝謝你,先生。經過一番沉重的挖掘和混亂之後,我一直無法讓雄辯的彎曲我喜歡的方式,並得出了相同的結論。 –

相關問題