2013-05-29 42 views
0

我想讓我的模型在多個數據庫中執行一些操作。假設我的模型是用戶類。它擴展了SynchroAR類(SynchroAR擴展CActiveRecord)。 在用戶類別:Yii - 使用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()方法,但我猜它在相同的數據庫上執行了兩次,因爲第二個數據庫中的數據沒有被更改。爲什麼?

回答

2

我想這是因爲$ db是靜態的。

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

我會嘗試這樣的事情,在你的SynchroAR類。

 
... 
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(); 
} 
+0

謝謝你!它完美的作品。 – Joe

+0

不幸的是,它不是很好。它僅適用於'更新'場景。當我插入行時 - 它不起作用。它只保存在默認數據庫中。 – Joe

+0

對不起,但我必須撤銷'已解決',因爲保存只在更新數據時才起作用,而不是在插入新數據時起作用。 – Joe

相關問題