[英]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.