On this page
用户评论api
创建相关文件
php
// 创建评论控制器
php think make:controller api/v1/Comment
// 创建评论模型
php think make:model Comment
// 创建评论验证器
php think make:validate CommentValidate
controller层:application\api\controller\v1\Comment.php
php
<?php
namespace app\api\controller\v1;
use think\Controller;
use think\Request;
use app\common\controller\BaseController;
use app\common\validate\CommentValidate;
use app\common\model\Comment as CommentModel;
class Comment extends BaseController
{
// 用户评论
public function comment(){
(new CommentValidate())->goCheck();
(new CommentModel())->comment();
return self::showResCodeWithOutData('评论成功');
}
}
route层:route\route.php
php
// 用户操作(绑定手机)
Route::group('api/:v1/',function(){
// 用户评论
Route::post('post/comment','api/v1.Comment/comment');
})->middleware(['ApiUserAuth','ApiUserBindPhone','ApiUserStatus']);
validate层:application\common\validate\CommentValidate.php
php
protected $rule = [
'fid'=>'require|integer|>:-1|isCommentExist',
'data'=>'require|print',
'post_id'=>'require|integer|>:0|isPostExist',
];
BaseValidate层: application\common\validate\BaseValidate.php
php
// 评论是否存在
protected function isCommentExist($value,$rule='',$data='',$field='')
{
if ($value==0) return true;
if (\app\common\model\Comment::field('id')->find($value)) {
return true;
}
return "回复的评论已不存在";
}
model层:application\common\model\Comment.php
php
// 评论
public function comment(){
$params = request()->param();
// 获得当前用户id
$userid = request()->userId;
$comment = $this->create([
'user_id'=>$userid,
'post_id'=>$params['post_id'],
'fid'=>$params['fid'],
'data'=>$params['data']
]);
// 评论成功
if ($comment) {
if ($params['fid']>0) {
$fcomment = self::get($params['fid']);
$fcomment->fnum = ['inc', 1];
$fcomment -> save();
}
return true;
}
TApiException('评论失败');
}