php Yii1使用第二个数据库连接访问模型类,多个数据库连接

lymnna71  于 2023-03-28  发布在  PHP
关注(0)|答案(1)|浏览(114)

我使用了多个数据库连接。
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'
        ),
    ),
)

当使用模型类时,第二个数据库连接(远程数据库- db2)记录不会更新
请帮助我解决这个问题。

模型类

class Modelclass extends CActiveRecord
{
    // model class code
}
vhipe2zx

vhipe2zx1#

在Yii 1中访问多个数据库连接
步骤如下:

Step1:在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:在组件中创建新类访问第二个数据库连接(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.'));
            }

        }

    }
}

Step 3:使用组件中创建的类扩展第二个数据库中的模型类

class Modelclass extends Db2ActiveRecord
{
    // model class code
}

相关问题