2017-10-12 132 views
0
Edit: 
I dont think its the same issue as: 
https://stackoverflow.com/questions/40022929/laravel-relationship-error-undefined-property-illuminate-database-eloquent-col 
because in that issue hasMany relationship is used which returns an array but i used belongsTo which should return a certain object. 

我有一个数据库结构,其中我有一个多对多的用户和公司表之间的关系。为此我有一个交叉引用表company_user。另外每个用户在公司中都有一定的角色,所以交叉引用表也有一个role_id。问题是,由于某种原因,当我尝试从交叉引用表中检索角色时,出现异常。Laravel - belongsTo关系在自定义枢轴模型不起作用

这是我如何定义的公司模式的关系:

public function users() { 
    return $this->belongsToMany('App\User')->withPivot('role_id')->using('App\CompanyUser'); 
} 

现在,如果我只是试图从枢一切ROLE_ID工作正常:

@foreach($company->users as $user) 
    {{$user->pivot->role_id}} // this displays correct role_id 
@endforeach 

,但我也需要的数据所以我在自定义数据透视中定义了一个关系。这里是整个模型:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Relations\Pivot; 

class CompanyUser extends Pivot 
{ 
    public function role() 
    { 
     return $this->belongsTo('App\Role'); 
    } 
} 

,我试图访问它是这样的:

@foreach($company->users as $user) 
    {{$user->pivot->role()->id}} 
@endforeach 

但是这给了我一个例外:

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$id 

我缺少什么?

+0

的可能的复制[Laravel关系错误:未定义的属性:1号线照亮\数据库\雄辩\收藏:: $ ID](https://stackoverflow.com/questions/ 40022929/laravel-relationship-error-undefined-property-illuminate-database-eloquent-col) –

回答

2

尝试更改为

@foreach($company->users as $user) 
    {{$user->pivot->role->id}} 
@endforeach 
+1

好的答案 - 如果它包含了几行有关OP原始代码错误的信息,以及为什么修复它! – sgress454