0

I have two database with these config file

    'db' => require(__DIR__ . '/db.php'),
    'db2' => require(__DIR__ . '/db2.php'),

db.php file

return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;port=**;dbname=**',
'username' => '**',
'password' => '**',
'charset' => 'utf8'];

db2.php file

return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;port=**;dbname=**',
'username' => '**',
'password' => '**',
'charset' => 'utf8'];

when I want use db2 database config in migrate I get error

public function init()
{
    $this->db = 'db2';
    parent::init();
}

public function up()
{
    $this->createTable('logs', [
        'id' => $this->primaryKey()->unsigned(),
        'type' => $this->string(8)->notNull(),
        'data' => $this->string(255)->notNull(),
        'created_at' => $this->integer()->notNull()->unsigned(),
    ]);
}

public function down()
{
    $this->dropTable('logs');
}

error:

Exception 'yii\base\InvalidConfigException' with message 'Failed to instantiate component or class "db2".'

anyone try use migration with two databases?

1 Answers1

1

Don't override your db in the init method, do it in the attribute instead:

public $db = 'db2';

public function up()
{
    $this->createTable('logs', [
        'id' => $this->primaryKey()->unsigned(),
        'type' => $this->string(8)->notNull(),
        'data' => $this->string(255)->notNull(),
        'created_at' => $this->integer()->notNull()->unsigned(),
    ]);
}

public function down()
{
    $this->dropTable('logs');
}

UPDATE

I just read the code again and your way was correct when override the init method, but did you add your config to the console.php file?

'db' => require(__DIR__ . '/db.php'),
'db2' => require(__DIR__ . '/db2.php'),

they should be in the the console.php file too.

Jackson Tong
  • 657
  • 1
  • 6
  • 18