On this page
获取当前文章的评论列表api
controller层:application\api\controller\v1\Post.php
php
// 文章评论列表
public function comment(){
// 验证文章id
(new PostValidate())->goCheck('detail');
$list = (new PostModel) -> getComment();
return self::showResCode('获取成功',['list'=>$list]);
}
route层:route\route.php
php
Route::group('api/:v1/',function(){
// 获取当前文章的所有评论
Route::get('post/:id/comment','api/v1.Post/comment');
});
model层:application\common\model\Post.php
php
// 关联评论
public function comment(){
return $this->hasMany('Comment');
}
// 获取评论
public function getComment(){
$params = request()->param();
return self::get($params['id'])->comment()->with([
'user'=>function($query){
return $query->field('id,username,userpic');
}
])->select();
}
Comment模型:application\common\model\Comment.php
php
// 关联用户
public function user(){
return $this->belongsTo('User','user_id');
}