@@ -338,26 +338,44 @@ Now if we run the `migrate` command, the above configurations will take effect
...
@@ -338,26 +338,44 @@ Now if we run the `migrate` command, the above configurations will take effect
without requiring us to enter the command line options every time. Other command options
without requiring us to enter the command line options every time. Other command options
can be also configured this way.
can be also configured this way.
### Managing migrations for multiple databases
The preferred way to manage migrations for multiple databases is to create a directory for each database's migrations, and then run the migrate command for each database like this:
This way you have full control on which database corresponds to which migration directory. Another benefit is that migration history is kept in the database migrations are applied to. So each database would keep it's migration history.
Alternative approach is set the database, which the migration should be performed on, in the migration class. To do so, we need to override the [[yii\db\Migration::init()]] method as follows:
The above command will apply *all* migrations found in the default migration path to the `db2` database.
If your application works with multiple databases, some migrations should be applied to one database while
some others should be applied to another database. In this case, it is recommended that you create a base
migration class for each different database and override the [[yii\db\Migration::init()]] method like the following,
```php
```php
publicfunctioninit()
publicfunctioninit()
{
{
parent::init();
$this->db='db2';
$this->db=Yii::$app->dbConnectionId;
parent::init();
}
}
```
If a migration needs to be applied to one database, you create a migration class by extending from the corresponding
base migration class.
Now if you run the `yii migrate` command, each migration will be applied to the corresponding database.
Because each migration has harcoded the DB connection, the `--db` option of the `migrate` command will have no effect.
If you still want to support changing DB connection via the `--db` option, you may take the following alternative
approach to work with multiple databases.
For each database, create a migration path and save all corresponding migration classes there. To apply migrations,
where `dbConnectionId` is ID of the database application component. This approach is much faster to implement and use, you create and apply migrations running migrate command as usual, without providing extra parameters. We recommend using [[yii\db\Migration::init()]] with caution though, as in this case the migration history is saved to the database configured in [[yii\console\controllers\MigrateController::db]]
- database which MigrateController currently operates on.