2014-12-20 32 views
-1

我在Yii2詢問有關LoginForm的問題如何更改LoginForm中的表用戶

安裝Yii後,我在裏面找到了默認的帶有登錄窗體的Web。此表格將連接到表名「用戶」

然後我修改默認值以創建具有不同登錄表單的新網站。而且我還爲登錄名「db_user」創建了新表。我仍然在commons/model中使用名爲「LoginForm」的默認模型進行登錄。這裏是代碼

<?php 
namespace common\models; 

use Yii; 
use yii\base\Model; 

/** 
* Login form 
*/ 
class LoginForm extends Model 
{ 
public $username; 
public $password; 
public $rememberMe = true; 

private $_user = false; 


/** 
* @inheritdoc 
*/ 
public function rules() 
{ 
    return [ 
     // username and password are both required 
     [['username', 'password'], 'required'], 
     // rememberMe must be a boolean value 
     ['rememberMe', 'boolean'], 
     // password is validated by validatePassword() 
     ['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, $params) 
{ 
    if (!$this->hasErrors()) { 
     $user = $this->getUser(); 
     if (!$user || !$user->validatePassword($this->password)) { 
      $this->addError($attribute, 'Incorrect username 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->rememberMe ? 3600 * 24 * 30 : 0); 
    } else { 
     return false; 
    } 
} 

/** 
* Finds user by [[username]] 
* 
* @return User|null 
*/ 
public function getUser() 
{ 
    if ($this->_user === false) { 
     $this->_user = User::findByUsername($this->username); 
    } 

    return $this->_user; 
} 


} 

當我讀了我混淆的代碼後,因爲在這個模型中沒有聲明將用於登錄的表名。我嘗試登錄後,它只適用於那些記錄在「用戶」表中的用戶。

如何將默認表從「user」更改爲「db_user」?

謝謝。

+0

試試這個如何 - http://www.bsourcecode.com/yiiframework2/yii-2-user-login-from-database/ – clonerworks

+0

我不understan d爲什麼我拒絕了投票。至少先解釋一下 –

回答

0

LoginForm模型只是表單的模型,而不是用戶模型。

User::findByUsername($this->username); 

正如你看到的,在LoginForm的使用DB模式是用戶,如果你在你的文件的模型去/ user.php的,你會看到一行:

public static function tableName() 
{ 
    return '{{%user}}'; 
} 

修改成:

public static function tableName() 
{ 
    return 'db_user'; 
} 

好運

+0

謝謝,我明白了 –

相關問題