How to set YII2 Multiple DB Configurable?

how to set database configurable in active record ?

This my file : app\models\multi_db\Devices;




<?php

namespace app\models\multi_db;


use yii\db\ActiveRecord;


class Devices extends ActiveRecord

{ 

     private static $dbConn;


     public function __construct($config=[])

     {

        switch ($config['server']) {

        case '2':

            self::$dbConn = \Yii::$app->dbtwo;

            break;

        case '3':

            self::$dbConn = \Yii::$app->dbthree;

            break;          

        default:

            self::$dbConn = \Yii::$app->dbone;

            break;

        }

     }


     public static function getDb()

     {

        return self::$dbConn;

     }


     public function findDevice($id)

     {

        return self::findOne($id);

     }

}



This my code to get device :

$model = new Devices([‘server’ => 3]);

$device = $model->findDevice(1);

But this generate error:

Undefined index: server

I think the constructor not set in findDevice method?

How can I fix this?

Rather than in model I would use the switch in the configuration.

Try to make something like this for your db configuration





$whatEver=1;


if(my condiction) {

	$whatEver=2;

} else {

	$whatEver=3;

}


    	switch ($whatEver) {

    	case 1:

        	$dbConn = [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=db1',  'username' => 'user1', 'password' => 'pwd1'];

        	break;

    	case 2:

        	$dbConn = [ 'class' => 'yii\db\Connection', 'dsn' =>  'mysql:host=localhost;dbname=db2',  'username' => 'user2', 'password'  => 'pwd2'];

        	break;      	

    	case 3:

        	$dbConn = [ 'class' => 'yii\db\Connection', 'dsn' =>  'mysql:host=localhost;dbname=db3',  'username' => 'user3', 'password'  => 'pwd3'];

        	break;

    	}


return [

	'components' => [

    	'db' => $dbConn

	],

];