Y
Y
Yaroslav Studenikin2020-11-12 12:27:37
Yii
Yaroslav Studenikin, 2020-11-12 12:27:37

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',
];


Accordingly, in the config/web.php file, I added these lines: All according to the template of the main database db.php When defined in the model:
$db2 = require __DIR__ . '/db2.php';
'db2' => $db2,

public static function getDb()
    {
        return \Yii::$app->db2;
    }

Error, component missing. Maybe I’m not connecting in the right way, but I tried various suggested methods ... Tell me what’s wrong, please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-11-12
@yar_stun

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',
    ],
],
];

Then in your application code in ActiveRecord models you need to override the getDb() method.
public function getDb() {
    return Yii::$app->db1;
}

//db2
public function getDb() {
    return Yii::$app->db2;
}

Models in which you have overridden the getDb() method, specifying db1 as the connection to the database, will receive data from the database db1, and vice versa:
ModelName::find()->select('*')->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question