1. Declare more database Connection in config file
To use multiple database connection you can try putting another db component into the configuration file at protected/config/main.phparray(
'components'=>array(
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=yii_blog',
'emulatePrepare' => true,
'username' => 'YOUR_USERNAME',
'password' => '*************',
'charset' => 'utf8',
'tablePrefix' => 'tbl_',
),
'anotherDb' => array(
'connectionString' => 'mysql:host=adserver2;dbname=anotherDB',
'username' => 'YOUR_USERNAME',
'password' => '***********',
...
'class' => 'CDbConnection' // DO NOT FORGET THIS!
),
),
The parameters should generally follow the pattern of the first entry, but you must include the class parameter ('class' => 'CDbConnection' ) in the second so that Yii knows you're defining a DB Connection object. It will fail without this.You can access them by calling like that
$firstDb = Yii::app()->db; $firstDb->active = true; // etc, then $secondDb = Yii::app()->anotherDb; $secondDb->active = true;
or GetDbConnection() override in model class like the following:
class YourModel extends CActiveRecord {
...
private $anotherDb = null;
protected function getDbConnection()
{
if (self::$anotherDb !== null)
return self::$anotherDb;
else
{
self::$anotherDb = Yii::app()->anotherDb;
if (self::$anotherDb instanceof CDbConnection)
{
self::$anotherDb->setActive(true);
return self::$anotherDb;
}
else
throw new CDbException(Yii::t('yii','Active Record requires'.
'a "db" CDbConnection application component.'));
}
}
Note: This entry will be update more if We know another way to do