[英]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.