Can I simultaneously work with two databases in Yii2? If yes, then tell me by example please !!!!

    1 answer 1

    Yes. Here is a short translation of the answer from English StackOverflow, which will help you. (The original questions and answers are here: https://stackoverflow.com/questions/27254540/yii-2-0-multiple-database-connection )

    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 the code of your application 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; } 

    The models in which you redefined the getDb() method, specifying db1 as a connection to the database, will receive data from the db1 database, and vice versa:

     ModelName::find()->select('*')->all();