【发布时间】:2019-11-16 19:34:47
【问题描述】:
我正在尝试构建一个基本的 Laravel Vue 评论系统来学习两者。
现在我正在尝试在特定的帖子文章上显示所有 cmets。
我的控制器返回 json_response。
public function comments(Post $post)
{
return response()->json(
$post->comments
);
}
一切正常,我使用 Axios get 方法得到以下 json 响应。
[
{
"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 雄辩的关系。
在 Blade 中,如果我将响应作为数据返回到 View 中,我可以显示用户,如下所示:
@foreach($post->comments as $comment)
{{ $comment->user->username }}
@endforeach
如何在我的 json 响应中传递用户与 cmets 的关系,以从 user_id 值获取评论的用户?
【问题讨论】:
标签: php json laravel vue.js axios