yii2:如何使用两个数据库表登录?

时间:2016-06-18 06:22:00

标签: php phpmyadmin yii2-basic-app

我在数据库table1和table2中有两个表,我正在尝试使用table1和table2用户名和密码登录。我有table1和table2的单独模型。 我的LoginForm是

class LoginForm extends Model
{

public $email;
public $password;
public $rememberMe = true;
public $status;
private $_user = false; 
/**
 * @return array the validation rules.
 */

public function rules()
{
    return [
        [['email', 'password'], 'required'],
        ['rememberMe', 'boolean'],
        ['password', 'validatePassword'],
    ];
}

/**
 * Validates the password.
 * This method serves as the inline validation for password.
 *
 * @param string $attribute the attribute currently being validated
 * @param array $params the additional name-value pairs given in the rule
 */

 public function validatePassword($attribute)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();
        $pass= (table1::find()->where(['Password'=>$this->password] ) OR (table2::find()->where(['Password'=>$this->password] ) ->one()));
        if (!$user || !$pass) {
            $this->addError($attribute, 'Incorrect email or password.');
        }
    }
    }
/**
 * Logs in a user using the provided username and password.
 * @return boolean whether the user is logged in successfully
 */

public function login()
{
    if ($this->validate()) {
        return Yii::$app->user->login($this->getUser(), $this->status, $this->rememberMe ? 3600*24*30 : 0);
    }
    return false;
}

/**
 * Finds user by [[username]]
 *
 * @return User|null
 */

public function getUser()
{
    if ($this->_user === false) {
    $this->_user =Table1::findByEmail_id([$this->email ]) OR Table2::findByEmail_id([$this->email ]);
    }
    return $this->_user ;   
}

}

我试过这样但我无法登录,我收到了错误

PHP致命错误 - yii \ base \ ErrorException 在非对象上调用成员函数validatePassword()

任何人都可以帮助我 提前致谢

1 个答案:

答案 0 :(得分:0)

您必须在Table1和Table2中复制此功能

public function validatePassword($password)
{
    return Yii::$app->security->validatePassword($password, $this->password_hash);
}

您还可以参考以下链接: http://www.bsourcecode.com/yiiframework2/yii-2-user-login-from-database/