2017-09-02 66 views
1

我有型號A,B和C.甲hasOne與B和B的hasMany關係與C.如何使用方法鏈接從Laravel Eloquent的遙遠關係模型中檢索數據?

//Model Code 

class A extends Model 
{ 
    //This relates A and B 
    public function relateBC(){ 
     return $this->hasOne('App\B','aid','aid'); 
    } 
} 

class B extends Model 
{ 
    //Inverse relationship with Model A 
    public function relateBC(){ 
     return $this->belongsTo('App\A','aid','aid'); 
    } 

    //This relates B and C 
    public function relateBC(){ 
     return $this->hasMany('App\C','bid','bid'); 
    } 
} 


class C extends Model 
{ 
    //Inverse relationship with Model B 
    public function post(){ 
     return $this->belongsTo('App\B','bid','bid'); 
    } 
} 

下面代碼返回數據關係從模型B

App\A::find(id)->relateAB()->get(); 

下面從型號代碼的返回數據ç

App\B:find(id)->relateBC()->get();   

下面的代碼拋出BadMethodException。方法涉及BC()不存在。

App\A::find(id)->relateAB->relateBC()->get();  

+0

歡迎使用stackoverflow。請,你能提供一些你的具體問題的代碼嗎?這可以證明你嘗試了多遠,它會幫助其他成員更好地理解你的問題,當時,你會給他們一個你的問題的背景。請檢查這些鏈接:https://stackoverflow.com/help/mcve和https://stackoverflow.com/help/how-to-ask –

回答

0

試試這個:

$distantRelations = App\A::find($id)->relateAB->relateBC; 

時一樣,你回來了HasOne relationship object(你可以調用->get()的對象)的方法(即->relateAB())訪問,而當作爲一個神奇的屬性訪問(即 - >相關AB),您可以找回模型實例(您可以訪問關係relateBC的對象)。

可以使用方法,而不是魔法屬性,但請記住,你是那麼誰有權決定關係類型之一(一個與許多),並呼籲無論是在底層->get()->first()分別查詢生成器:

$distantRelations = App\A::find($id) 

    // 'relateAB' is a singular relation, 
    // so we'll need to call 'first()' 

    ->relateAB()->first() // > App\B 

    // 'relateBC' is a 'many' relation, 
    // so we'll need to call 'get()' 

    ->relateBC()->get(); // > App\C[]|\Illuminate\Support\Collection 

HasOne調用first()

您可以親眼目睹HasOne調用first()爲您在查詢生成器at this line,通過訪問該關係作爲魔術屬性執行。

HasMany調用get()

您可以親眼目睹HasMany上查詢生成器at this line,通過訪問關係魔法屬性執行的呼籲get()你。

+0

試過,我得到一個BadMethodCallException消息'調用未定義的方法Illuminate \ Database \ Query \ Builder :: relateAB()' – Fynix

+0

請更新您的問題與相關的代碼(去掉不必要的東西)。包括3個模型和相關的關係方法。還有一些關於你數據庫表的信息(它們的名字,主鍵列的名字)會有所幫助。 –

+0

我已經包含了模型代碼。 – Fynix

0

在數據透視表中聲明瞭A模型和B模型的主鍵,即作爲兩個表的外鍵

相關問題