manish23 Posted September 7, 2015 Share Posted September 7, 2015 Hi, Is there a way to change the default db connection for a particular controllers actions. I want to switch between two database connection in my action, how do I do it ? I have configured both the database in my main.php file, like: 'db'=>array( 'connectionString' => 'mysql:host=1.1.1.1;dbname=mydb', 'emulatePrepare' => true, 'username' => 'root', 'password' => '1111', 'charset' => 'utf8', ), 'db2'=>array( 'class'=>'CDbConnection', 'connectionString' => 'mysql:host=2.2.2.2;dbname=mydb', 'emulatePrepare' => true, 'username' => 'root', 'password' => '2222', 'charset' => 'utf8', ), How do I switch between these two database connection in my controller's action ? Link to comment Share on other sites More sharing options...
Brent Knigge Posted September 8, 2015 Share Posted September 8, 2015 Hello, You need to use the getDB method of the ActiveRecord class. http://www.yiiframework.com/doc-2.0/yii-db-activerecord.html#getDb()-detail If you wanted your model code to switch between different DB, then I suppose you could set a public attribute in the model which would then could be returned from getDB. There is some more information here: http://stackoverflow.com/questions/27254540/yii-2-0-multiple-database-connection Hope that helps, brent Link to comment Share on other sites More sharing options...
Recommended Posts