Yii使用ActiveRecord(ORM)存取DB功能時,在 config/main.php 中預設一組DB connection
'db'=>array(
.....
)
若要設定多組DB connection,可override CActiveRecord的public method - getDbConnection,
通常為了重覆利用,會建立一個class去繼承CActiveRecord,Ex:
class secondDbNameActiveRecord extends CActiveRecord {
public static $secondDbName;
public function getDbConnection() {
if(self::$secondDbName !==null){
return self::$secondDbName;
}else{
self::$secondDbName = Yii::app()->secondDbName;
if(self::$secondDbName instanceof CDbConnection){
self::$secondDbName->setActive(true);
return self::$secondDbName;
}else{
throw new CDbException(Yii::t('yii','Active Record requires a "secondDbName" CDbConnection application component.'));
}
}
}
}
記得在config/main.php的components下加入一組新設定
'secondDbName'=>array(
'connectionString' => 'mysql:host=127.0.0.1;dbname=secondDbName',
'emulatePrepare' => true,
'username' => 'xxxx',
'password' => 'xxx',
'charset' => 'utf8',
'class' => 'CDbConnection'
),
欲使用的model只要繼承剛建立的class即可
class mytable extends secondDbNameActiveRecord {
}
沒有留言:
張貼留言