Changing the database dinamically

I have an app that use two identical databases, db1 and db2 both defined in config.

In each model of the app I define by default

public static function getDb() {

	return Yii::$app->db1;


But in some cases, depending on the user choice in a view, I need to change dynamically the database db1 by the database db2.

How I do that in the controller when I create an instance of a model with

$model = new MyModel();

In short I need something like this

$model = new MyModel(put here the $selectedDbByUser);

I solved the problem using two identical models (MyModel 1 and MyModel2) each pointing to his database db1 or db2 but I think it is not an elegant solution.

Thanks a lot for your help.

If you have identical models then a "more elegant way" to handle it would be to extend them.

put MyModel in common\models.

put MyModel1 & MyModel2 in frontend\models.

put all of your code in MyModel

in MyModel1/2 only put

class MyModel1 extends common\models\MyModel


   public static function getDb() {

      return Yii::$app->db1;



The same for MyModel2.

Then do the same selecting that you already do to select model 1 or 2

I did a quick look at the docs and didn’t see anything, but I think there is/should be a Yii::$app->setDb() $model->setDb() method.