0

I want my model to do some action into multiple databases. Let's say my model is User class. It extends SynchroAR class (SynchroAR extends CActiveRecord). In User Class:

protected function afterSave()
{
    if($this->goSynchro)
        $this->runSynchro('save');
    parent::afterSave();
}

In SynchroAR:

protected function runSynchro($method)
{
    $this->goSynchro = false;
    foreach($this->entryConns as $conn)
    {
        parent::$db = $conn;
        parent::$db->setActive(true);
        call_user_func(array($this, $method));
    }
    $this->goSynchro = true;
    parent::$db = Yii::app()->usersdb;
    parent::$db->setActive(true);
}

$entryConns is an array containing connections where the the $method should be applied. For now I have one entry in $entryConns. I turned on CWebLogRoute and it actually does save() method but I guess it executes it twice on the same database, because data at the 2nd database is not being changed. Why?

Joe
  • 2,551
  • 6
  • 38
  • 60

1 Answers1

2

I would guess it's because $db is static.

Inspired by: http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii/

I would try something like this, in your SynchroAR class.

...
private $_currentDb = null;
public function setDb($db = null)
{
    if($db === null)
    {
        $this->_currentDb = null;
        parent::$db->setActive(true);
    }
    else
    {
        $this->_currentDb = $db;
        $this->_currentDb->setActive(true);
    }
}
public function getDbConnection()
{
    if($this->_currentDb !== null)
        return $this->_currentDb;
    else
        return parent::$db;
}
protected function runSynchro($method)
{
    $this->goSynchro = false;
    foreach($this->entryConns as $conn)
    {
        $this->setDb($conn);
        call_user_func(array($this, $method));
    }
    $this->goSynchro = true;
    $this->setDb();
}
jborch
  • 1,146
  • 6
  • 15
  • It is not working totally great unfortunately. It works only in 'update' scenario. When I insert rows - it is not working. It saves only in default db. – Joe May 29 '13 at 13:52
  • Sorry but I have to revoke the 'solved' because saving works only when updating data, not in case inserting new one. – Joe May 31 '13 at 13:20
  • 1
    It does not work when you insert new records. What you have to do is to use `setIsNewRecord(true)` after every execute of `save()` method plus except the first call of the `save()` you should call it `save(false)` to disable validation. – Joe Jun 03 '13 at 11:36