网站首页 博客 Yii 1.1操作多个数据库
Yii提供的ActiveRecord使用起来非常方便,那么它能操作多个数据库吗,答案是可以的。
首先需要在配置文件config/main.php中增加一个数据库组件,例如
'db_history'=>array( 'class' =>'CDbConnection', 'connectionString' => 'mysql:host=localhost;dbname=history', 'emulatePrepare' => true, 'username' => 'root', 'password' => '123456', 'charset' => 'utf8', )
然后定义一个对应此数据库的ActiveRecord基类,例如
class CActiveRecord_history extends CActiveRecord
{
//重写数据库连接
public function getDbConnection() {
return Yii::app()->db_history;
}
}然后就可以定义该数据库中所有表的ActiveRecord类,继承上面的基类,例如
class Visit_history extends CActiveRecord_history
{
private $_tableName;
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
$this->_tableName = 'visit'; //库中对应的表名
return $this->_tableName;
}
}这样就可以很方便的操作另外一个数据库了。