问题
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