可以配置多个数据库连接和上面提到的@crafter在迁移命令提起,也可以覆盖在运行时数据库连接,并使其动态。
以下是覆盖默认Yii迁移控制器类和使用多个数据库迁移的一些步骤。
1:创建下控制台/控制器新的控制器类(MigrateController)/ MigrateController
2:添加下面的内容到上述创建的类(MigrateController)(控制台/控制器/ MigrateController)。
```
<?php
/**
* Yii MigrateController class that will override default up functionality & used dynamic connection based on your settings, or DB lists
* @author Nadeem Akhtar <[email protected]>
* Date: 1/19/16
* Time: 4:34 PM
*/
namespace console\controllers;
use Yii;
use yii\console\controllers\MigrateController as BaseMigrateController;
use yii\helpers\Console;
/**
* Test controller
*/
class MigrateController extends BaseMigrateController {
/*
* init function
*
*
* */
public function init() {
parent::init();
}
/**
* Upgrades the application by applying new migrations.
* For example,
*
* ```
* yii migrate # apply all new migrations
* yii migrate 3 # apply the first 3 new migrations
* ```
*
* @param integer $limit the number of new migrations to be applied. If 0, it means
* applying all available new migrations.
*
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
* Example call: **./yii migrate/migrate-up**
*/
public function actionMigrateUp($limit = 0)
{
// Get all databases from companies settings
$companies = Companies::find()->where('settings')->all();
foreach($companies as $company) {
$this->setRunTimeConnection($company['settings']); // This will set dynamic connection based on your record in DB
$this->stdout("New migration founds for ".$company['name'].".\n", Console::FG_GREEN); // print message to show which migration is runing for which company
$this->actionUp($limit);
}
}
/*
* Dynamic connection
* Override default **Yii::$app->db** settings
*
* */
public function setRunTimeConnection($setting) {
$host = $setting['DB_host'];
$dbName = $setting['DB_name'];
$dsn = "mysql:host=$host;dbname=$dbName"; //Host & Database
Yii::$app->db->dsn = $dsn;
Yii::$app->db->username = $setting['DB_username'];
Yii::$app->db->password = $setting['DB_password'];
}
}
3:添加迁移控制器的地图将在控制台/配置/ main.php
.
.
.
'controllerMap' => [
'migrate' => 'console\controllers\MigrateController',
],
4:现在创建一些虚拟的迁移和添加三个或四个数据库你的$阵列列表
5:你已经完成了所有!
根据您的要求,您可以在此上播放更多内容。
请参阅此链接http://www.yiiframework.com/doc-2.0/guide-db-migrations.html#migrating-multiple-databases – GAMITG