2017-05-25 81 views
0

我對laravel很陌生,並且已經建立了幾個模型和視圖等。無論如何,我正在嘗試做的是,我有一個用戶模型和一個團隊模型。字段'id'是用戶team_id的外鍵。 用戶可以加入任何球隊和他加入的球隊,其ID將存儲在用戶的'team_id'中。 我打算這樣做,使用team_id字段從團隊模型中獲取數據,如團隊名稱並將其顯示在刀片​​視圖中。Laravel 5.4無法通過刀片中的外鍵訪問數據

這裏是我的用戶模型代碼:

 protected $fillable = ['name', 

     'email', 
     'password', 
     'date_of_birth', 
     'team_id', /*references id in teams model*/ 
     'matches_played', 
     'goals_scored', 
     'preffered_position', 
     'phone_number', 
     'role', 
     'ban_status', 
     'team_captain' 
    ]; 





    /** 
    * The attributes that should be hidden for arrays. 
    * 
    * @var array 
    */ 
    protected $hidden = [ 
     'password', 'remember_token', 
    ]; 


    public function Teams(){ 
     return $this->belongsTo('App\Teams', 'team_id'); 
    } 


} 

這是我的球隊型號代碼:

`protected $primaryKey = 'id'; 
protected $fillable = ['team_name', 'matches_played', 
'matches_lost', 'goals_scored', 'goals_conceded', 
'captain_name']; 

public function User(){ 
    return $this->hasMany('App\User','id'); 
} 

`

public function showMembers(){ 
    $users = User::with(array('Teams'))->get(); 
    return view('admin.members')->with('users', $users); 
    } 

`

` 和這個如何我試圖顯示它在刀片: {{$用戶> team_id-> TEAM_NAME}}

但不是顯示它的,我不斷獲取:

Trying to get property of non-object (View: D:\Code\PHP\Code\PlayOn\resources\views\admin\members.blade.php) 

任何幫助將是不勝感激!

回答

0

這裏有幾件事情你做錯了。

一是急於負載的關係,在這種情況下,球隊的關係,這是做它的方式:

$users = User::with('Teams')->get(); 

最後,通過收集循環,你需要做的事情像這樣:

@foreach($users as $user) 
    {{ $user->Teams->team_name }} 
@endforeach 
+0

它的工作!非常感謝! –