简体   繁体   English

在yii 2中使用两个数据库

[英]work with two databases in yii 2

I have two database with these config file 我有两个带有这些配置文件的数据库

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

db.php file db.php文件

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

db2.php file db2.php文件

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 当我想在迁移中使用db2数据库配置时出现错误

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".' 消息“无法实例化组件或类” db2”的异常'yii \\ base \\ InvalidConfigException'。

anyone try use migration with two databases? 有人尝试对两个数据库使用迁移吗?

Don't override your db in the init method, do it in the attribute instead: 不要在init方法中覆盖您的数据库,而应在属性中执行:

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? 我只是再次阅读了代码,重写init方法时您的方法是正确的,但是您是否将配置添加到console.php文件中?

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

they should be in the the console.php file too. 它们也应该在console.php文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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