无法在 laravel 的 post 视图中获取评论的用户数据
unable to fetch user data of comment in a post's view in laravel
我有三个模型和对应的tables。用户,Post,发表评论。
用户列 table 是 id、姓名、电子邮件。
post 列 table 是 id,title,body。
评论栏table是id,user_id,post_id,comment.
用户模型有如下功能:
public function comments(){
return $this->hasMany('App\Comment');
}
Post型号有如下功能:
public function comments(){
return $this->hasMany('App\Comment');
}
评论模型有以下两个功能:
public function user(){
$this->belongsTo('App\User');
}
public function post(){
$this->belongsTo('App\Post');
}
单个post显示在PostController中的功能如下:
public function show($slug)
{
$post = Post::where('slug', $slug)->first();
return view('post.show')->withPost($post);
}
在 show.blade.php 中,我正在尝试实现此功能:
@foreach($post->comments as $comment)
<p>
{{$comment->user->name}}
</p>
@endforeach
为什么说关系方法必须 return 一个对象会抛出错误?
你需要return
关系,所以你的代码变成:
public function user(){
return $this->belongsTo('App\User');
}
public function post(){
return $this->belongsTo('App\Post');
}
我有三个模型和对应的tables。用户,Post,发表评论。 用户列 table 是 id、姓名、电子邮件。 post 列 table 是 id,title,body。 评论栏table是id,user_id,post_id,comment.
用户模型有如下功能:
public function comments(){
return $this->hasMany('App\Comment');
}
Post型号有如下功能:
public function comments(){
return $this->hasMany('App\Comment');
}
评论模型有以下两个功能:
public function user(){
$this->belongsTo('App\User');
}
public function post(){
$this->belongsTo('App\Post');
}
单个post显示在PostController中的功能如下:
public function show($slug)
{
$post = Post::where('slug', $slug)->first();
return view('post.show')->withPost($post);
}
在 show.blade.php 中,我正在尝试实现此功能:
@foreach($post->comments as $comment)
<p>
{{$comment->user->name}}
</p>
@endforeach
为什么说关系方法必须 return 一个对象会抛出错误?
你需要return
关系,所以你的代码变成:
public function user(){
return $this->belongsTo('App\User');
}
public function post(){
return $this->belongsTo('App\Post');
}