Create a component
create a class file under protected\components named RActiveRecord.php
using this code
class RActiveRecord extends CActiveRecord { private static $dbadvert = null; protected static function getAdvertDbConnection() { if (self::$dbadvert !== null) return self::$dbadvert; else { $User=User::model()->findByPk(Yii::app()->user->id); $db_name = $user->db_name; self::$dbadvert = Yii::createComponent(array( 'class' => 'CDbConnection', // other config properties... 'connectionString'=>"mysql:host=localhost;dbname=".$db_name, //dynamic database name here 'enableProfiling' => true, 'enableParamLogging' => true, 'username'=>'root', 'password'=> '', //password here 'charset'=>'utf8', 'emulatePrepare' => true, 'enableParamLogging'=>true, 'enableProfiling' => true, )); Yii::app()->setComponent('dbadvert', self::$dbadvert); if (self::$dbadvert instanceof CDbConnection) { Yii::app()->db->setActive(false); Yii::app()->dbadvert->setActive(true); return self::$dbadvert; } else{ throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.')); } } } }
Select dynamic Database name
change this line according to your use
$User=User::model()->findByPk(array('id'=>Yii::app()->user->id)); $db_name = $user->db_name
just need the database name
Extend from RActiveRecord
extend all models from RActiveRecord and call function getDbConnection()
class model-name extends RActiveRecord { public function getDbConnection() { return self::getAdvertDbConnection(); }
Thats it!! :-)