2017-10-12 61 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