How to change table users in LoginForm

☆樱花仙子☆ 提交于 2019-12-13 08:46:06

问题


I am asking about LoginForm in Yii2

After I install Yii, I get the default Web with login form inside it. This form will connect to table name "user"

Then I modify the default to create new website with different login form. And also I create new table for login name "db_user". I still use the default model named "LoginForm" in commons/model for login. Here is the code

<?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;
}


 }

After I read the code I confuse, because in this model does not declare the table name that will be used for login. After i tried login it only work for users those were recorded in "user" table.

How can I change the default table from "user" to "db_user"?

Thanks.


回答1:


The LoginForm model is just a model for the form, not for the User model.

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

As you see, the db model used in LoginForm is User, if you go in your file models/User.php you will see a line:

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

Change that to:

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

Good luck



来源:https://stackoverflow.com/questions/27576197/how-to-change-table-users-in-loginform

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!