I read this question yii 2.0 multiple database connection , and use the answer of @Ali MasudianPour.
I follow the first step:
First you need to configure your databases like below:
return [
'components' => [
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=database1',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=database2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
],
]; ?>
But in my configuration in my db
it gives me this error:
The configuration for the "db" component must contain a "class" element.
This is because db
component is main and required and you simply omitted its declaration.
Rename db1
and db2
for example to db
and db1
accordingly:
return [
'components' => [
// Main connection
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=database1',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
// Another connection
'db1' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=database2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
],
]; ?>
Update:
Note that for the basic application db
is configured in separate file config/db.php
and then required in main config config/web.php
like so:
'db' => require(__DIR__ . '/db.php'),
So you can configure main connection in db.php
and add additional below as db1
.
Simply you just have to create separate file for each database .
config/db
->
'class' => 'yii\\db\\Connection', 'dsn' => 'mysql:host=localhost;dbname=database1', 'username' => 'root', 'password' => '', 'charset' => 'utf8',
To access another db create file in config named db1.php
add add another db configuration.
config/db1
->
'class' => 'yii\\db\\Connection', 'dsn' => 'mysql:host=localhost;dbname=database2', 'username' => 'root', 'password' => '', 'charset' => 'utf8',
In config->web.php
add
'db' => require(__DIR__ . '/db.php'), 'db1' => require(__DIR__ . '/db1.php'),
To access the Model:
public static function getDb() { return Yii::$app->db1; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.