我试图让作者的用户名在页面上显示评论时显示他们写的评论附近。我有一个错误“试图获取非对象的属性'名称”
控制器:
public function index(Site $site)
{
$comments=Comments::where('siteId', $site->id)->get();
return view('admin.comments.show', compact('comments'));
}
视图:
@foreach($comments as $comment)
{{$comment->user->name}}
@endforeach
用户模型:
public function comments()
{
return $this->hasMany(Comments::class);
}
评论模型:
public function comments()
{
return $this->belongsTo(User::class);
}
我想用关系。谢谢你的帮助! :)
将Comment
模型中的关系更改为:
public function user()
{
return $this->belongsTo(User::class);
}
这应该工作。
在用户模型中:
public function comments()
{
return $this->hasMany(Comment::class); // change Comments to Comment here
}
在评论模型中:
public function user()
{
return $this->belongsTo(User::class);
}