我正在尝试构建一个基本的Laravel Vue评论系统,以学习两者。
现在,我试图在特定帖子文章中显示所有评论。
我的控制器返回json_response。
public function comments(Post $post)
{
return response()->json(
$post->comments
);
}
一切正常,我得到以下JSON响应Axios Get Method。
[
{
"id":1,
"post_id":1,
"user_id":1,
"body":"Post Comment 1",
"created_at":null,
"updated_at":null,
"deleted_at":null
},
{
"id":2,
"post_id":1,
"user_id":1,
"body":"Post comment 2",
"created_at":null,
"updated_at":null,
"deleted_at":null
}
]
我正在用VUE显示所有数据,但我不确定如何在Comments
和Users
模型上获得HTE关系雄辩。
在刀片中,如果我在 View
中返回响应作为数据,则可以显示用户:
@foreach($post->comments as $comment)
{{ $comment->user->username }}
@endforeach
我如何通过我的JSON响应中的注释将用户的关系传递给用户,以使用户从user_id value中获取评论?
我在laracasts的帮助下解决了。
我必须更改对
的回应public function comments(Post $post)
{
return response()->json(
$post->comments->load('user');
);
}