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 . 问题是,由于某些原因,当我尝试从交叉引用表中检索角色时,我得到一个异常 .
以下是我如何定义公司模型中的关系:
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
我错过了什么?
1 回答
尝试换到