Multiple Database Select database based on login user id

You are viewing revision #5 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.

next (#6) »

  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!!