簡體   English   中英

在yii 2中使用兩個數據庫

[英]work with two databases in yii 2

我有兩個帶有這些配置文件的數據庫

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

db.php文件

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

db2.php文件

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

當我想在遷移中使用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');
}

錯誤:

消息“無法實例化組件或類” db2”的異常'yii \\ base \\ InvalidConfigException'。

有人嘗試對兩個數據庫使用遷移嗎?

不要在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');
}

更新

我只是再次閱讀了代碼,重寫init方法時您的方法是正確的,但是您是否將配置添加到console.php文件中?

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

它們也應該在console.php文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM