Search code examples
phpyiiyii-componentsyii1.x

Yii1 access model class using 2nd database connection. Multiple database connection


I've used multiple database connection.

main.php

'components'=>array(
    'db'=>array(
        'connectionString' => 'mysql:host=localhost;dbname=testdrive',
        'emulatePrepare' => true,
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ),
    'db2'=>array(
            'connectionString' => 'mysql:host=remotelocalhost;dbname=seconddb',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
            'class'=>'CDbConnection'
        ),
    ),
)

When model class used the second database connection(remote database - db2) record is not updated

Plz help me to resolve this issue.

Model Class

class Modelclass extends CActiveRecord
{
    // model class code
}

Solution

  • Access multiple database connection in Yii1

    Below are the steps:

    Step1: Create database connection string in config/main.php

    'components'=>array(
        'db2'=>array(
            'class'=>'CDbConnection',
            'connectionString' => 'mysql:host=RemoteHostIpAddress;dbname=Remote_DB_Name',
            'emulatePrepare' => true,
            'username' => 'Remote_DB_User_Name',
            'password' => 'Remote_DB_Password',
            'charset' => 'utf8',
            'enableParamLogging' => true,
        ),
    
        'db'=>array(
            'class'=>'CDbConnection',
            'connectionString' => 'mysql:host=localhost;dbname=DB_Name',
            'emulatePrepare' => true,
            'username' => 'DB_User_Name',
            'password' => 'DB_Password',
            'charset' => 'utf8',
            'enableParamLogging' => true,
        ),
    )
    

    Step2: Create new class in components to access 2nd database connection(db2)

    class Db2ActiveRecord extends CActiveRecord
    {
        public static $db2;
    
        public function getDbConnection()
        {
    
            if(self::$db2!==null)
                return self::$db2;
            else
            {
                self::$db2=Yii::app()->db2;
                self::$db2->connectionString;
    
                if(self::$db2 instanceof CDbConnection)
                {
                    self::$db2->setActive(true);
                    return self::$db2;
                }
                else{
                    throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
                }
    
            }
    
        }
    }
    

    Step3: extends the model class from 2nd database using class created in components

    class Modelclass extends Db2ActiveRecord
    {
        // model class code
    }