Example:

$query = (new \yii\db\Query())->select()->from('table');

The request is executed for a database that is db.

This option is $query = (new \yii\db\Query()) ->select) ->from('table') ->all(\Yii::$app->db2); does not fit, since it will go to ActiveDataProvider

How to change db (database) in Query Builder?

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

To use multiple databases in Yii2, do the following:

Add to config / web.php

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

Contact:

 //k db1 Yii::$app->db1->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll(); //к db2 Yii::$app->db2->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll(); 

If you are using the ActiveRecord model, then:

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

Successful coding ...