我正在构建一个简单的通知系统。
我可以通过 Auth::user()->notifications
获取登录用户的通知,但我的最终目标是获取通知来源的用户信息。
我希望得到一个最终结果
foreach( Auth::user()->notifications AS $n)
{
echo $n->from->username;
}
目前这会引发“尝试获取非对象的属性”错误。
通知表;
id
user_id - notification for this user
from_user_id - notification from this 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');
}
通知.php;
public function to()
{
return $this->belongsTo('App\User', 'user_id');
}
public function from()
{
return $this->belongsTo('App\User', 'from_user_id');
}
最佳答案
首先你需要在通知表中设置一个外键;然后用户可以有一个通知。和许多同时。通知。属于一个用户和许多通知。可以属于一个用户。因此,在 Notification 模型上,您像这样设置关系 belongsTo;
外键:
$table->foreign('from')->refrences('id')->on('users')->onDelete('cascade');
然后是关系:
public function users()
{
return $this->belongsTo('App\User');
}
然后从 Controller 中你可以像这样获取用户信息;
$userName= Notification::users()->name;
在你的情况下,你指向错误作为返回你将只得到关系类型而不是数据对象,因为你像非方法一样调用 from
。你应该这样做:
foreach( Auth::user()->notifications AS $n)
{
echo $n->from()->username;
}
关于php - Laravel Eloquent 关系链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44752284/