A
A
Artem Prokhorov2021-10-04 12:27:01
Yii
Artem Prokhorov, 2021-10-04 12:27:01

How to connect to multiple databases at once?

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=name',
            'username' => 'login',
            'password' => 'password',
            'charset' => 'utf8',
        ],
    ],
];

How to access multiple databases at once?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FernandoErrNando, 2021-10-04
@kotcich

In the config write:

<?php
return [
    'components' => [
       'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=name',
            'username' => 'login',
            'password' => 'password',
            'charset' => 'utf8',
        ],
        'db2' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=db2',
            'username' => 'user',
            'password' => 'pass',
            'charset' => 'utf8',
        ],
       
];

Then, in models that use the 2nd database, just specify it:
public static function getDb()
    {
        return Yii::$app->db2;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question