2

有2张桌子:

1)用户( id, login, password, user_roles_id,...)
2) user_roles ( role_id, role_name,...)

我需要从第一个加入第二个表的表中获取用户数据user_role_id = role_id

对于这两个表,我都创建了模型:

1)应用\模型\Users.php

  public function getUserRoles()
    {
        return  $this->hasOne(userRoles::className(), ['role_id' => 'user_roles_id']);
    }

2) app\models\UserRoles.php

public function getUsers()
    {
        return $this->hasMany(Users::className(), ['user_roles_id' => 'role_id']);
    }

对于现场认证,我正在使用另一个类:

应用\模型\用户.php

namespace app\models;

use app\models\Users as DbUser;

class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $email;
public $user_roles_id;
public $role_id;
public $role_name;
public $member_since;
public $name;
public $surname;

/**
 * @inheritdoc
 */
public static function findIdentity($id) {
    $dbUser = DbUser::find()
            ->joinWith('userRoles')
            ->where([
                "id" => $id
            ])

            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}

/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $userType = null) {

    $dbUser = DbUser::find()
            ->joinWith('userRoles')
            ->where(["accessToken" => $token])
            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}

/**
 * Finds user by username
 *
 * @param  string      $username
 * @return static|null
 */
public static function findByUsername($username) {
    $dbUser = DbUser::find()
            ->joinWith('userRoles')
            ->where([
                "username" => $username
            ])
            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}
}

这不会给出任何错误,但仍然无法获取活动用户的角色名称。这是vardumpYii::$app->user->identity

object(app\models\User)#80 (12) { 
["id"]=> int(2) 
["username"]=> string(4) "demo" 
["password"]=> string(32) "fe01ce2a7fbac8fafaed7c982a04e229" 
["authKey"]=> string(10) "test101key" 
["accessToken"]=> string(9) "101-token" 
["email"]=> string(12) "test@mail.ml" 
["user_roles_id"]=> int(1) 
["role_id"]=> NULL 
["role_name"]=> NULL 
["member_since"]=> int(1442061812) 
["name"]=> string(6) "Kirsan" 
["surname"]=> string(6) "Kayfat" }
4

0 回答 0