简体   繁体   中英

Yii Migrations with multiple databases - specify DB?

We have a huge app built on Yii.

So far migrating was done by copy-pasting SQL dumps in phpliteadmin/phpmyadmin, but that's not very convenient.

I want to use CDbMigration s for it, with yiic migrate .

The issue is that we have two databases - a small sqlite one for config and settings, and large mysql for storing some historical records.

How do I specify what database the migration belongs to?

This is the basic migration structure, for illustration.

class do_stuff extends CDbMigration
{
    public function up()
    {
        // create table
    }

    public function down()
    {
        // drop table
    }
}

In your config.php file, specify your database connections in the components array.

    'db1'=>array(
                'class'=>'CDbConnection',
                'connectionString' => 'mysql:charset=utf8mb4;host=localhost;dbname=dbname1',
                'username' => 'root',
                'password' => 'root',
                'charset' => 'utf8',
            ),
    'db2'=>array(
                'class'=>'CDbConnection',
                'connectionString' => 'mysql:charset=utf8mb4;host=localhost;dbname=dbname2',
                'username' => 'root',
                'password' => 'root',
                'charset' => 'utf8',
            ),

Then in your migration, you can do the following:

protected $dbConnection1;
protected function getDbConnection1()
{
    if (null !== $this->dbConnection1) {
        return $this->dbConnection1;
    }

    return $this->dbConnection1 = Yii::app()->getComponent('db1');
}

Repeat for your second connection.

Then use those methods to get the CDbConnection for each database, from which you can create commands to execute.

You can use CDbMigration::setDbConnection() to change the default, or override the getDbConnection() method. This is similar to another proposed solution, but it had a typo and it needed to be a public function, so I include here the fix.

In your migration, include the following (change db1 for the defined connection name in your configuration files):

protected $dbConnection1;
public function getDbConnection()
{
   if (null !== $this->dbConnection1) {
      return $this->dbConnection1;
   }

   return $this->dbConnection1 = Yii::app()->getComponent('db1');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM