Yii2-user: How to create admin user in batch mode?

寵の児 提交于 2019-12-08 10:31:45

问题


When deploying my application there is of course always an admin user.

How can I create such an admin user as a first user without any interaction ...

  • ... by means of SQL?
  • ... using a Yii2-migration?

回答1:


Found it. There is an easy way to do this with Yii2 builtin migrations.

In Yii2-user there are some hooks we can use to create users.

This code has to be inserted in a migration. after creating a new migration ./yii migrate/create, preferably after creating initial tables in the database:

use yii\db\Transaction;
use app\models\user\User;

public function safeUp()
{
    $transaction = $this->getDb()->beginTransaction();
    $user = \Yii::createObject([
        'class'    => User::className(),
        'scenario' => 'create',
        'email'    => 'admin',
        'username' => 'admin@example.com',
        'password' => 'mysecret',
    ]);
    if (!$user->insert(false)) {
        $transaction->rollBack();
        return false;
    }
    $user->confirm();
    $transaction->commit();
}

The skeleton code can be found in ./migrations/....

Don't forget to add database config parameters in ./config/db.php and the user module in ./config/console.php



来源:https://stackoverflow.com/questions/42516985/yii2-user-how-to-create-admin-user-in-batch-mode

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