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

关注用户api


创建相关文件

php
// 创建粉丝关注模型
php think make:model Follow

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

php
// 关注
public function follow(){
    (new UserValidate())->goCheck('follow'); 
    (new UserModel())->ToFollow();
    return self::showResCodeWithOutData('关注成功');
}

route层:route\route.php

php
// 用户操作(绑定手机)
Route::group('api/:v1/',function(){
	// 关注
    Route::post('follow','api/v1.User/follow');
})->middleware(['ApiUserAuth','ApiUserBindPhone','ApiUserStatus']);

validate层:application\common\model\UserValidate.php

php
protected $rule = [
    'follow_id'=>'require|integer|>:0|isUserExist'
];
protected $scene = [
    'follow'=>['follow_id'],
];

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

php
// 关联关注
public function withfollow(){
    return $this->hasMany('Follow','user_id');
}
// 关注用户
public function ToFollow(){
    // 获取所有参数
    $params = request()->param();
    // 获取用户id
    $user_id = request()->userId;
    $follow_id = $params['follow_id'];
    // 不能关注自己
    if($user_id == $follow_id) TApiException('非法操作',10000,200);
	// 获取到当前用户的关注模型
    $followModel = $this->get($user_id)->withfollow();
    // 查询记录是否存在
    $follow = $followModel->where('follow_id',$follow_id)->find();
    if($follow) TApiException('已经关注过了',10000,200);
    $followModel->create([
        'user_id'=>$user_id,
        'follow_id'=>$follow_id
    ]);
    return true;
}