How to create user in database manually in Yii2?

2020-05-07 10:01发布

I do import of users from a csv file to the database. In csv file I have some kinda username and password string. So how do I create a new user manually? As I understand I need to getPasswordHash and generateAuthKey (last one generates random string). But probably I loose something important since when I try to log in I get an error that Username or Password is incorrect. Did anyone ever experienced such situation? Thanks in advance.

2条回答
看我几分像从前
2楼-- · 2020-05-07 10:24

This should be the minimum required in your case. $username and $password are raw values taken from the CSV. Remember that there will be validation applied.

$user = new User();
$user->username = $username;
$user->setPassword($password);
$user->generateAuthKey();

return $user->save();
查看更多
相关推荐>>
3楼-- · 2020-05-07 10:32

I think you forgot to set an active status of new User. You should check it in Login method of User model in your app, or in actionLogin of SiteController. For example, in my app the login method is:

public function login()
{
    if ($this->validate() and $this->getUser()->status !== User::INACTIVE_STATUS) {
       return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
    }
    return false;
}

If you show your code we can help you faster)

So if you are importing a list of users from a csv file, you will probably process this in a loop, try:

foreach ($csv_data as $user_data) {
   $user = new User();
   $user->setPassword($password);
   $user->username = $user_data->username // or anything else, depending on your code
   $user->status = 1  // or = User::STATUS_ACTIVE, depending on your code
   $user->save();
}
查看更多
登录 后发表回答