2017-08-01 41 views
1

我很抱歉,如果我的问题没有意义......如何从laravel中的两个表之间的雄辩关系访问第三个表数据?

我有这两个表区,和地址,并通过外键都与......这里是区域和地址车型

class Area extends Model 
{ 

    protected $table='areas'; 

    public function sections(){ 

     $this->hasMany(Area::class,'area','id'); 
    } 

    public function address(){ 
     $this->belongsTo(Address::class,'id'); 
    } 
} 

class Address extends Model 
{ 
    protected $table='address'; 

    public function area(){ 
     return $this->hasMany(Area::class,'id'); 
    } 
} 

和我有第三个表区连接到区域表。

我的问题,我可以做,可以从部分访问地址表的数据雄辩的关系“一节表区连接没有解决”

class Section extends Model 
{ 
    protected $table ='sections'; 

    protected $fillable =[ 
     'sec_code', 
     'area', 
     'id', 
    ]; 


    public function beneficiaries(){ 
     return $this->hasMany(Beneficiary::class,'ben_sec','id'); 
    } 

    public function area_sec(){ 
     return $this->belongsTo(Area::class,'area'); 
    } 

    public function address(){ 
    // need the eloquent relation if could 
} 

} 

谢谢

回答

2

把它作为一个PROPERT:从您的区域关系第一,所以代码会是这样访问它Ÿ不是一个方法:

$model->area_sec; 
0

你可以得到的数据

class Section extends Model 
{ 
    protected $table ='sections'; 

    protected $fillable =[ 
     'sec_code', 
     'area', 
     'id', 
    ]; 


    public function area_sec(){ 
     return $this->belongsTo(Area::class,'area'); 
    } 

    public function address(){ 
     return $this->area_sec->address; 
    } 

} 
+1

谢谢你,它的作品,但我得到这个#eagerLoad:数组:1 [▼ “地址”=>关闭{#181}▶ ] #loc我怎样才能访问这个eagerload数组 – Tariq

+0

你调用该方法后得到的? –

+0

我得到与上面的代码相同的错误:调用未定义的方法Illuminate \\ Database \\ Query \\ Builder :: addEagerConstraints() –