2017-01-18 92 views
0

我已經使用了多個數據庫連接。Yii1使用第二個數據庫連接的訪問​​模型類。多個數據庫連接

main.php

'components'=>array(
    'db'=>array(
     'connectionString' => 'mysql:host=localhost;dbname=testdrive', 
     'emulatePrepare' => true, 
     'username' => 'root', 
     'password' => '', 
     'charset' => 'utf8', 
    ), 
    'db2'=>array(
      'connectionString' => 'mysql:host=remotelocalhost;dbname=seconddb', 
      'emulatePrepare' => true, 
      'username' => 'root', 
      'password' => '', 
      'charset' => 'utf8', 
      'class'=>'CDbConnection' 
     ), 
    ), 
) 

當模型類使用的第二個數據庫連接(遠程數據庫 - DB2)記錄未更新

PLZ幫我解決這個問題。

模型類

class Modelclass extends CActiveRecord 
{ 
    // model class code 
} 
+0

如何你使用連接.....你可以請張貼更多的代碼 – lakshay

+0

最後我找出解決方案。謝謝lakshay。 – Kailas

回答

1

訪問多個數據庫中Yii1

下面連接的步驟是:

第一步:在配置創建數據庫連接字符串/ main.php

'components'=>array(
    'db2'=>array(
     'class'=>'CDbConnection', 
     'connectionString' => 'mysql:host=RemoteHostIpAddress;dbname=Remote_DB_Name', 
     'emulatePrepare' => true, 
     'username' => 'Remote_DB_User_Name', 
     'password' => 'Remote_DB_Password', 
     'charset' => 'utf8', 
     'enableParamLogging' => true, 
    ), 

    'db'=>array(
     'class'=>'CDbConnection', 
     'connectionString' => 'mysql:host=localhost;dbname=DB_Name', 
     'emulatePrepare' => true, 
     'username' => 'DB_User_Name', 
     'password' => 'DB_Password', 
     'charset' => 'utf8', 
     'enableParamLogging' => true, 
    ), 
) 

第二步:創建組件的新類來訪問第二個數據庫連接(DB2)

class Db2ActiveRecord extends CActiveRecord 
{ 
    public static $db2; 

    public function getDbConnection() 
    { 

     if(self::$db2!==null) 
      return self::$db2; 
     else 
     { 
      self::$db2=Yii::app()->db2; 
      self::$db2->connectionString; 

      if(self::$db2 instanceof CDbConnection) 
      { 
       self::$db2->setActive(true); 
       return self::$db2; 
      } 
      else{ 
       throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.')); 
      } 

     } 

    } 
} 

第三步:從第2個數據庫使用組件創建類擴展模型類

class Modelclass extends Db2ActiveRecord 
{ 
    // model class code 
} 
+0

好.................... – lakshay