我有两个带有这些配置文件的数据库
'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');
}
错误:
异常' yii \ base \ InvalidConfigException' with message'无法实例化组件或类" db2"。'
是否有人尝试使用两个数据库进行迁移?
答案 0 :(得分:1)
不要在init方法中覆盖db,而是在属性中执行:
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文件中。