我在Yii2中询问LoginForm
安装Yii之后,我在其中获得了带有登录表单的默认Web。此表单将连接到表名“user”
然后我修改默认设置以使用不同的登录表单创建新网站。我还为登录名“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 :(得分:0)
LoginForm模型只是表单的模型,而不是用户模型。
User::findByUsername($this->username);
如您所见,LoginForm中使用的db模型是User,如果你进入你的文件models / User.php,你会看到一行:
public static function tableName()
{
return '{{%user}}';
}
将其更改为:
public static function tableName()
{
return 'db_user';
}
祝你好运