Jump to content
Larry Ullman's Book Forums
manish23

Switching Between Database Connection In Yii

Recommended Posts

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 ?

 

Share this post


Link to post
Share on other sites

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 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...