在yii2 ActiveRecord中连接2个表

时间:2015-09-13 10:44:12

标签: php mysql activerecord yii2 yii2-basic-app

得到2张桌子:

1)用户idloginpassworduser_roles_id,...)
2) user_roles role_idrole_name,...)

我需要从第一个表格中获取用户数据,并在user_role_id = role_id上添加第二个表格。

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

1) app \ models \ 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']);
    }

对于网站上的身份识别,请使用其他课程

应用\模型\ user.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);
}
}

这不会给出任何错误,但仍然无法获得活动用户的role_name。以下是vardump的{​​{1}}。

Yii::$app->user->identity

0 个答案:

没有答案