【发布时间】:2023-03-21 01:06:01
【问题描述】:
我有一个 Laravel 和 Vue.js 应用程序,我通过 API 将 cmets 发送到帖子页面。现在我想通过该 API 获取该帖子的 cmets,这是我尝试过的:
commentController
public function index(){
$comment = Comment::with('post')->get();
return new CommentResource($comment);
}
评论模型
public function post(){
return $this->belongsTo(Post::class);
}
后模型
public function comments(){
return $this->hasMany(Comment::class);
}
这是我的 Api 路由
Route::resource('comment','CommentController');
最后这是我点击时得到的结果
http://localhost:8000/api/comment
这是所有的 cmets,而不是属于特定帖子的 cmets
{
"data": [{
"id": 33,
"body": "a",
"user_id": 1,
"user_email": "a",
"user_name": "a",
"status": 0,
"post_id": 9,
"created_at": "2019-03-25 08:50:55",
"updated_at": "2019-03-25 08:50:55",
"post": null
}, {
"id": 32,
"body": "a",
"user_id": 1,
"user_email": "a",
"user_name": "a",
"status": 0,
"post_id": 9,
"created_at": "2019-03-25 08:50:55",
"updated_at": "2019-03-25 08:50:55",
"post": null
}, {
"id": 31,
"body": "a",
"user_id": 1,
"user_email": "a",
"user_name": "a",
"status": 0,
"post_id": 9,
"created_at": "2019-03-25 08:50:55",
"updated_at": "2019-03-25 08:50:55",
"post": null
}, {
"id": 30,
"body": "a",
"user_id": 1,
"user_email": "a",
"user_name": "a",
"status": 0,
"post_id": 1,
"created_at": "2019-03-25 08:50:55",
"updated_at": "2019-03-25 08:50:55",
"post": null
}]
}
知道如何将相关评论发送到特定帖子吗?
【问题讨论】: