0

我希望我的模型对多个数据库执行一些操作。假设我的模型是用户类。它扩展了 SynchroAR 类(SynchroAR 扩展了 CActiveRecord)。在用户类中:

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

在 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是一个数组,其中包含$method应该应用 的连接。目前我在$entryConns. 我打开CWebLogRoute它,它实际上执行save()了方法,但我猜它在同一个数据库上执行了两次,因为第二个数据库中的数据没有被更改。为什么?

4

1 回答 1

2

我猜这是因为 $db 是静态的。

灵感来自: http ://www.yiiframework.com/wiki/123/multiple-database-support-in-yii/

我会在您的 SynchroAR 课程中尝试这样的事情。

...
私人 $_currentDb = null;
公共函数 setDb($db = null)
{
    如果($db === 空)
    {
        $this->_currentDb = null;
        父::$db->setActive(true);
    }
    别的
    {
        $this->_currentDb = $db;
        $this->_currentDb->setActive(true);
    }
}
公共函数 getDbConnection()
{
    if($this->_currentDb !== null)
        返回 $this->_currentDb;
    别的
        返回父::$db;
}
受保护的函数 runSynchro($method)
{
    $this->goSynchro = false;
    foreach($this->entryConns as $conn)
    {
        $this->setDb($conn);
        call_user_func(array($this, $method));
    }
    $this->goSynchro = true;
    $this->setDb();
}
于 2013-05-29T12:13:14.203 回答