D
D
Dmitry Kim2016-07-04 09:01:14
Yii
Dmitry Kim, 2016-07-04 09:01:14

How to change database component on the fly in ActiveRecord YII2?

There is one yii2-advanced and two sites in it. The migration files are common and apply to both sites.
In the configuration file of the console application, the component is not specified db, instead of it there are db1and db2.
Accordingly, migrations are launched like this: yii migrate/up --db=db1and yii migrate/up --db=db2.
Everything works, but(!): in one of the migrations, a default user is created:

if (!$email = ArrayHelper::getValue(Yii::$app->params, 'developerEmail')) {
  if (!$email = ArrayHelper::getValue(Yii::$app->params, 'supportEmail')) {
    throw new InvalidConfigException('App must have a developer or support email');
  }
}

$user = new User();
$user->email  = $email;
$user->status = User::STATUS_ACTIVE;
$user->role   = User::ROLE_DEVELOPER;
$user->setPassword('654321');
$user->generateAuthKey();
$user->save();

An error occurs here, because the database component it dbis looking at is not specified User(). At first, I thought that by specifying a component in the migration, the db1yii migrate/up --db=db1application works with this base, but apparently not.
Tell me why this is so, and how to change the value on the fly $user->getDb().

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kim, 2016-07-04
@kimono

Heh, I've decided. If anyone is interested:

if (!$email = ArrayHelper::getValue(Yii::$app->params, 'developerEmail')) {
  if (!$email = ArrayHelper::getValue(Yii::$app->params, 'supportEmail')) {
    throw new InvalidConfigException('App must have a developer or support email');
  }
}

// нужно добавить компонент db используя текущую базу
Yii::$app->setComponents([
  'db' => $this->getDb(),
]);

$user = new User();
$user->email = $email;
$user->status = User::STATUS_ACTIVE;
$user->role = User::ROLE_DEVELOPER;
$user->setPassword('654321');
$user->generateAuthKey();
$user->save();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question