Skip to content
关注公众号,获取新课通知
【重要通知】uniapp实战社区交友交流群更换为:602180461,靓仔/靓女可以重新申请加入哦~

用户顶踩api


创建相关文件

php
// 创建顶踩控制器
php think make:controller api/v1/Support
// 创建顶踩模型
php think make:model Support
// 创建顶踩验证器
php think make:validate SupportValidate

controller层:application\api\controller\v1\Support.php

php
<?php

namespace app\api\controller\v1;

use think\Controller;
use think\Request;
use app\common\controller\BaseController;
use app\common\model\Support as SupportModel;
use app\common\validate\SupportValidate;

class Support extends BaseController
{
    // 用户顶踩
    public function index(){
        (new SupportValidate())->goCheck();
        (new SupportModel())->UserSupportPost();
        return self::showResCodeWithOutData('ok');
    }

}

route层:route\route.php

php
// 用户操作(绑定手机)
Route::group('api/:v1/',function(){
    // 用户顶踩
    Route::post('support', 'api/v1.Support/index');
})->middleware(['ApiUserAuth','ApiUserBindPhone','ApiUserStatus']);

validate层:application\common\validate\SupportValidate.php

php
protected $rule = [
    'post_id'=>'require|integer|>:0|isPostExist',
    'type'=>'require|in:0,1'
];

BaseValidate层: application\common\validate\BaseValidate.php

php
// 文章是否存在
protected function isPostExist($value, $rule='', $data='', $field=''){
	if (\app\common\model\Post::field('id')->find($value)) {
	return true;
	}
	return "该文章已不存在";
}

model层:application\common\model\Support.php

php
// 用户顶踩文章
public function UserSupportPost(){
    $param = request()->param();
    // 获得用户id
    $userid = request()->userId;
    // 判断是否已经顶踩过
    $support = $this->where(['user_id'=>$userid,'post_id'=>$param['post_id']])->find();
    // 已经顶踩过,判断当前操作是否相同
    if ($support) {
        if ($support['type'] == $param['type']) TApiException('请勿重复操作',40000,200);
        // 修改本条信息
        return self::update(['id'=>$support['id'],'type'=>$param['type']]);
    }
    // 直接创建
    return $this->create([
        'user_id'=>$userid,
        'post_id'=>$param['post_id'],
        'type'=>$param['type']
    ]);
}