php 关注功能

150 阅读1分钟

关注关系产生的四种关系状态

1.互粉 2.已关注 3.我的粉丝 4.没有关系

需求分析

每一个用户都会有一个关注列表,一个粉丝列表。用户可以查看自己的关注,粉丝列表,也可以查看别人的关注,粉丝列表。并且,要展示列表里每个人与当前查看者的关注状态。

需要三个交集集合

  • 要查询的集合与我的互粉交集
  • 要查询的集合与我的关注交集
  • 要查询的集的与我的粉丝交集 不在这三个小交集中的用户就是无关系状态的用户。

我这里用的是REDIS

一.获取显示的用户列表

/**
 * 关注/粉丝 用户数据
 * @param $uid 用户ID
 * @param $type 2:粉丝;1:关注
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
public function userInfoArr($uid,$type,$page,$limit){
    ## 关注
    $follow_key = 'follow:'.$uid;
    ## 粉丝
    $fans_key = 'fans:'.$uid;
    if ($type==1){
        $re_list = Redis::smembers($follow_key);
    }else{
        $re_list = Redis::smembers($fans_key);

    }
    $ids = '';
    foreach ($re_list as $key => $value){
        if ($key){
            $ids .= ','.$value;
        }else{
            $ids .= $value;
        }
    }
    $where = [
        ['uid','in',$ids],
        ['status','=',1],
        ['is_del','=',0]
    ];
    return $this->selectList($where,'nickname,avatar,uid',$page,$limit)->toArray();
}

二.关注列表

/**
 * 关注/粉丝列表
 * @param int $follow_id 查看别人关注。粉丝 的用户ID  0为自己的
 * @param int $type 1:关注 2:粉丝
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
public function followList(int $follow_id=0,int $type=1){
    [$page, $limit] = $this->getPageValue();
    $uid = app('request')->uid();
    ## 关注
    $follow_key = 'follow:'.$uid;
    ## 粉丝
    $fans_key = 'fans:'.$uid;
    ## 自己关注和粉丝交集
    $fans_intersection = Redis::sinter($follow_key,$fans_key);
    $others_follow_intersection = [];
    $others_fans_intersection = [];
    if ($follow_id){
        $others_key = $type==1?'follow:'.$follow_id:'fans:'.$follow_id;
        ## 自己关注和 别人交集
        $others_follow_intersection = Redis::sinter($follow_key,$others_key);
        ## 自己粉丝和 别人交集
        $others_fans_intersection = Redis::sinter($fans_key,$others_key);
    }

    $user = new UserDao();
    $re = $user->userInfoArr($uid,$type,$page,$limit);
    foreach ($re as $k => $v){
        if(in_array($v['uid'], $fans_intersection)){
            $re[$k]['favoFlag'] = 3; //互相关注
        }else{
            if (!$follow_id){
                $re[$k]['favoFlag'] = $type;
            }else{
                if(in_array($v['uid'], $others_fans_intersection)) {
                    $userInfo['favoFlag'] = 2; //我的粉丝
                } else if(in_array($v['uid'], $others_follow_intersection)) {
                    $userInfo['favoFlag'] = 1; //我的关注
                } else{
                    $userInfo['favoFlag'] = 0; //无关系
                }
            }
        }
    }
    return $re;
}