繁体   English   中英

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

[英]yii2: How to login using two tables of database?

我在数据库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和表2中复制此函数

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM