Search code examples
phpactiverecordyiimultiple-databases

Yii - delete or save to multiple databases using CActiveRecord


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?


Solution

  • 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();
    }