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

<?php
    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!! :-)