2017-06-26 7 views
0

私は単純な通知システムを構築しています。 私はログインしたユーザーの通知をAuth::user()->notifications経由で取得できますが、私の最終目標は通知が送信されたユーザー情報も取得することです。私はLaravel Eloquent Relationship Chain

foreach(Auth::user()->notifications AS $n) 
{ 
    echo $n->from->username; 
} 

の最終的な結果を期待しています

現在、これは「非オブジェクトのプロパティを取得しようとすると」エラーがスローされます。

通知テーブル。

id 
user_id - notification for this user 
from_user_id - notification from this user 

User.php;

public function notifications() 
{ 
    return $this->hasMany('App\Notification', 'user_id', 'id')->orderBy('notifications.id','desc'); 
} 

public function notificationsUnread() 
{ 
    return $this->hasMany('App\Notification', 'user_id', 'id')->where('notifications.seen',null)->orderBy('notifications.id','desc'); 
} 

Notification.php;

public function to() 
{ 
    return $this->belongsTo('App\User', 'user_id'); 
} 

public function from() 
{ 
    return $this->belongsTo('App\User', 'from_user_id'); 
} 
+0

あなたが本当に問題が何であるか不明である場合は、具体的に何ができないのかを示すことができますか? – davejal

+0

通知の元になったユーザー情報、つまり通知が届いたユーザーのユーザー名を添付することができません。私は私の質問を更新しました。 –

+0

'Notification-> from;'を試してください。 – davejal

答えて

0

まず、テーブル通知に外部キーを設定する必要があります。その後、ユーザーはnotifを持つことができます。それと同時に多くの人たちがいます。ノート。ユーザーと多くのノーティフに属します。ユーザーに属することができます。したがって、通知モデルでは、belongsToというように関係を設定します。

外部キー:その後、

$table->foreign('from')->refrences('id')->on('users')->onDelete('cascade'); 

関係:

public function users() 
{ 
    return $this->belongsTo('App\User'); 
} 

次に、あなたがそうのようなユーザー情報を取得することができ、コントローラから。あなたのケースでは

$userName= Notification::users()->name; 

、あなたは非法のようfromを呼び出しているので、あなたは、唯一の関係タイプの代わりに、データオブジェクトを取得しますそれを間違ったinreturnを指しています。

foreach(Auth::user()->notifications AS $n) 
{ 
    echo $n->from()->username; 
}