2016-05-25 34 views
0

私はモデル間に多対多の関係を持っています。ユーザ&通知。Laravel Many To Manyメソッドの問題

ユーザーモデル:

public function notifications() 
{ 
    return $this->belongsToMany('Yeayurdev\Models\Notification', 'notifications_user', 'user_id', 'notification_id') 
     ->withPivot('notifier'); 
} 

通知モデル:

public function user() 
{ 
    return $this->belongsToMany('Yeayurdev\Models\User', 'notifications_user', 'notification_id', 'user_id'); 
} 

ピボットテーブル:私の見解では

ID  USER_ID  NOTIFICATION_ID 
1   2    1 

、私はそうのようなユーザーのためのすべての通知のリストを取得。雄弁\コレクション:: $のユーザー名\ \データベースを照らす:

@foreach (Auth::user()->notifications as $notification) 
    {{ $notification->user->username }} 
@endforeach 

問題は、私はその通知を持つユーザのユーザ名を取得しようとすると、私はエラー未定義のプロパティを取得することです。 "Username"は私のusersテーブルの列であり、単なる文字列です。私が "$ notificatin-> user"をすれば、それは私にコレクションを与えるので、私が間違っているところがわかりません。

ありがとうございます!

+0

括弧 '{{$ notification-> user() - > username}}'で試したことがありますか? – TheFallen

+0

あなたの質問に '$ notification-> user'の内容を追加できますか?ありがとう。 – haakym

答えて

6

あなたが言ったように、関係は多対多であるため、あなたのケースの$ notification-> userは、単一のユーザではなくユーザモデルの集合を返しています。あなたが最初のユーザのみが必要な場合は、すべての通知のためにすべてのユーザーをプリントアウトする必要がある場合は、単に、

{{ $notification->user()->first()->username }} 

を行い、その後、あなたはすべてのユーザーを通過するためにここにループが必要になります。

@foreach (Auth::user()->notifications as $notification) 
    @foreach($notification->user as $notificationUser) 
     {{ $notificationUser->username }} 
    @endforeach 
@endforeach 

私は将来的には混乱を避けるために、ユーザー(ユーザーに)関係を()名前の変更をお勧めします。

+0

うん、私はそれを考え出した。最初に$ notification-> userを実行して出力を表示したときに気付いたはずです。ありがとう! –