[SOLVED] Multiple databases?

Currently I'm using:

$this->connection = new CDbConnection(Yii::app()->params['db_dsn'], Yii::app()->params['db_user'], Yii::app()->params['db_pass']);


$this->connection->active = true;

to connect to a second database that is separate from the main application database. I have a few questions about it:

  1. Can I use active record and somehow tell it to use this specific connection for one model instance, but use the default connection elsewhere?

  2. If not, what is the correct way to generate update/insert/query sql with this connection?  Should I be constructing the sql by hand? 

Examples are appreciated, thanks.

I think you can just define multiple DB components in config main.php:

say we have a master db and a slave db, we can define them like this



'db_master'=>array(


			'connectionString'=>'mysql:host=localhost;dbname=db1',


			'username'=>'root',


			'password'=>'password',


			


		),


'db_slave'=>array(


			'connectionString'=>'mysql:host=anotherhost;dbname=db2',


			'username'=>'root2',


			'password'=>'password2',


			


		),


so that you can use

Yii::app()->db_master

to insert, update, delete

while use Yii::app()->db_slave for query purpose only.

I haven't tested this approach yet, so please correct me if these is any mistake.

Can you configure models to use a certain connection? if not, a ticket should be created for this.

To use multiple DBs for AR, you need to override its getDbConnection().

Can someone provide example of overriding getDbConnection in model

please  :)

Can someone provide example of overriding getDbConnection in model

Please check the code of CActiveRecord::getDbConnection() and you will see how.

Thanks, this is working great.

Please, example or cook book.

Here ya go:

http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii/