我使用过多个数据库连接。
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)时,记录未更新
Plz帮我解决了这个问题。
模型类
class Modelclass extends CActiveRecord
{
// model class code
}
答案 0 :(得分:1)
在Yii1中访问多个数据库连接
以下是步骤:
步骤1:在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,
),
)
步骤2:在组件中创建新类以访问第二个数据库连接(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.'));
}
}
}
}
步骤3:使用在组件
中创建的类从第2个数据库扩展模型类class Modelclass extends Db2ActiveRecord
{
// model class code
}