Answer the question
In order to leave comments, you need to log in
Working with multiple DBs Yii2?
Hello. I'm trying to connect to a second database. Googled a lot, looked at the info. Perhaps the information is outdated, or I do not understand something.
Created a new db2.php file in the config directory:
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;port=3307;dbname=example_1,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
$db2 = require __DIR__ . '/db2.php';
'db2' => $db2,
public static function getDb()
{
return \Yii::$app->db2;
}
Answer the question
In order to leave comments, you need to log in
First you need to create a component for each connection:
return [
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db1name',
'username' => 'db1username',
'password' => 'db1password',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=db2name',
'username' => 'db2username',
'password' => 'db2password',
],
],
];
public function getDb() {
return Yii::$app->db1;
}
//db2
public function getDb() {
return Yii::$app->db2;
}
ModelName::find()->select('*')->all();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question