mysql获取用户所有上级和下级ID(tp5.1/递归写法)

  • Post author:
  • Post category:mysql


    /**
     * @param $userId
     * @param $level
     * 获取用户上级ID
     */
    public static function getUpUser($userId, $level = 1)
    {
        $user = UserModel::get($userId);
        $data = [];
        if (empty($user->re_user_id)) {//没有上级返回空数组
            return [];
        }
        array_push($data, ['user_id' => $user->re_user_id, 'level' => $level]);//将上级ID和级别保存到data数组
        $data = array_merge($data, self::getUpUser($user->re_user_id, ++$level));//再继续查找是否还有上级ID并将数据合并到data数组

        return $data;
    }



    /**
     * @param array $userIds 以数组的形式传入需要查找用户的ID-->getDownUser([1])
     * 获取用户下级ID
     */
    public static function getDownUser(array $userIds)
    {
        $userIds = UserModel::where('re_user_id', 'in', $userIds)->column('user_id');//查找用户下级ID
        $data = [];
        if (empty($userIds)) {
            return [];
        }
        array_push($data, $userIds);//保存数据
        $data = array_merge($data, self::getDownUser($userIds));//继续查找下级ID

        return $data;
    }



版权声明:本文为qq_24334765原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。