Yii2-user:如何批量创建管理员用户? [英] Yii2-user: How to create admin user in batch mode?
问题描述
在部署我的应用程序时,当然总是有一个 admin
用户.
When deploying my application there is of course always an admin
user.
如何在没有任何交互的情况下创建这样一个 admin
用户作为第一个用户...
How can I create such an admin
user as a first user without any interaction ...
- ...通过SQL?
- ...使用 Yii2 迁移?
推荐答案
找到了.使用 Yii2 内置迁移有一种简单的方法可以做到这一点.
Found it. There is an easy way to do this with Yii2 builtin migrations.
在 Yii2-user 中,我们可以使用一些钩子来创建用户.
In Yii2-user there are some hooks we can use to create users.
必须在迁移中插入此代码.在创建一个新的迁移./yii migrate/create
之后,最好在数据库中创建初始表之后:
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();
}
框架代码可以在./migrations/...
中找到.
The skeleton code can be found in ./migrations/...
.
不要忘记在./config/db.php
中添加数据库配置参数和 ./config/console.php
Don't forget to add database config parameters in ./config/db.php
and the user module in ./config/console.php
这篇关于Yii2-user:如何批量创建管理员用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!