Multiple Database Connection : Select database based on login user id, Dynamic

You are viewing revision #9 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#8)next (#10) »

  1. Create a component
  2. Select dynamic Database name
  3. Extend from RActiveRecord

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;
             $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,
              'password'=> '', //password here
              'emulatePrepare' => true,
              'enableProfiling' => true,
			Yii::app()->setComponent('dbadvert', self::$dbadvert);
            if (self::$dbadvert instanceof CDbConnection)
                return self::$dbadvert;
                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

$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!! :-)