如何使用方法链接从Laravel Eloquent的遥远关系模型中检索数据?

问题描述:

我有型号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

欢迎使用*。请,你能提供一些你的具体问题的代码吗?这可以证明你尝试了多远,它会帮助其他成员更好地理解你的问题,当时,你会给他们一个你的问题的背景。请检查这些链接:https://*.com/help/mcve和https://*.com/help/how-to-ask –

试试这个:

$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

在数据透视表中声明了A模型和B模型的主键,即作为两个表的外键