I want to use to database connection at the same time. I got two servers having same database. I want to update both the database at the same time i.e On the add/update/delete on my app both the database needs to up updated accordingly. I have added the following in the main.php
'db2'=>array(
'connectionString' => 'mysql:host=hostname;dbname=dbanme',
'emulatePrepare' => true,
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
'tablePrefix' => 'tbl_',
'enableProfiling'=>true,
'enableParamLogging'=>true,
'class' => 'CDbConnection',
),
And then in my controller in the Add action :
public function actionCreate()
{
$model=new TestTransaction;
if(isset($_POST['TestTransaction']))
{
$originalDbConnection = Yii::app()->db;
$latin1DbConnection = Yii::app()->db2;
$model->attributes = $_POST['TestTransaction'];
if($model->save()) {
Yii::app()->setComponent("db",$latin1DbConnection);
$model->save();
Yii::app()->setComponent("db",$originalDbConnection);
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
But this is not working. Please help me out.
It's because AR model cache DB object.
public function getDbConnection()
{
if(self::$db!==null)
return self::$db;
else
{
self::$db=Yii::app()->getDb();
if(self::$db instanceof CDbConnection)
return self::$db;
else
throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
}
}
You may manualy set model $db attribute.
Try to set third parameter of setComponent to false:
if($model->save()) {
Yii::app()->setComponent("db",$latin1DbConnection, false); // set third parameter to false
$model->save();
Yii::app()->setComponent("db",$originalDbConnection, false);
$this->redirect(array('view','id'=>$model->id));
}
this disable merging new component with old one.
Thanks.