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

How do I retrieve data from a distant relationship model in Laravel Eloquent using method chaining?

我有模型 A、B 和 C。A 与 B 有一个关系,B 与 C 有许多关系。

//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');
    }
}

下面的代码 return 来自模型 B 的数据

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

下面的代码 return 来自模型 C 的数据

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

下面的代码抛出 BadMethodException。方法 relateBC() 不存在。

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

试试这个:

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

当作为方法访问时(即 ->relateAB()),你会得到 HasOne relationship object(你可以调用 ->get() 的对象),而当作为魔法访问时 属性(即 ->relateAB),你得到模型实例(你可以访问关系的对象relateBC)。

可以 使用方法而不是魔术 属性,但请记住,你是必须确定关系类型的人(一对. many),并分别在底层查询构建器上调用 ->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 在查询生成器 at this line 上为您调用 first(),通过访问关系作为魔术 属性.

执行

HasMany 调用 get()

您可以见证 HasMany 在查询构建器 at this line 上为您调用 get(),通过访问关系作为魔术 属性.

执行

在 Pivot table 中声明了 A 模型和 B 模型的主键,即作为 tables

的外键