2014-09-04 119 views
0

我有以下數據結構:如何在laravel-4中的三個模型之間建立關係?

Table t: 
     (PK)id 
      order_id (this links to table or's id) 


Table is: 
     (PK)id 
      tracking_id (this links to table or's tracking_id) 

Table or: 
     (PK)id (this links to table t's order_id) 
     (FK)tracking_id 

現在我的模型內(T.php)

我設置以下關係:

public function iS() 
{ 
    return $this->hasMany('is', 'tracking_id', 'order_id'); 
} 

現在很明顯,這並不因爲工作tracking_id與order_id不匹配。

如何將這三個表連接在一起,以便我可以檢索對應於t表的is數據?

我打電話是我這裏面控制器:

$o = O::with('t', 't.iS')->where('id','=',$id)->first(); (O is my model for "o" table) 

回答

1

您正在尋找hasManyThrough關係。 http://laravel.com/docs/eloquent#has-many-through

在本文檔例如:Country具有UsersUsers具有Posts。 每個國家要獲得職位定義:

class Country extends Eloquent { 

    public function posts() 
    { 
     return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id'); 
    } 

} 

在您的例子:TOrOr具有Is

+0

@neinI看到的例子,我試圖做我T內所以它是這樣的: 'return $ this-> hasManyThrough('或','Is')'沒有正常工作。我是否在錯誤的模型中創建了關係? – 2014-09-04 07:14:49

+0

您需要執行'$ this-> hasManyThrough('Is','Or');' – Nein 2014-09-04 07:25:06

+0

另外,您需要手動指定關係鍵。 (因爲默認的雄辯期望'or_id'和'is_id')。從文檔示例中得出,我認爲你需要做'$ this-> hasManyThrough('Is','Or','id','tracking_id');' – Nein 2014-09-04 07:33:47

相關問題