日期:2014-05-16  浏览次数:20467 次

Yii 实现数据库读写分离

实现一主一从,一主多从,多主多从的读写分离 。支持DAO,AR,其中Query builder只完成部分,需完善

调用

//AR
class User extends ActiveRecord
{
	public $useDbName= 'passport';
	//$this->dbWrite();
}
//$connection = $model->getDbConnection();
//DAO
$connection = Yii::app()->db->setDbName('passport');
$count = $connection->createCommand('SELECT COUNT(*) FROM film')->queryScalar();
$sql = 'SELECT film_id,title FROM film';
$dataProvider=new CSqlDataProvider($sql,array(
	'db'=> $connection,
	'totalItemCount'=>$count,
));
Yii::app()->db->getLastInsertID();

//Query Builder
$user = Yii::app()->db->setDbName('passport')->createCommand()
    ->select('id, username, profile')
    ->from('tbl_user u')
    ->join('tbl_profile p', 'u.id=p.user_id')
    ->where('id=:id', array(':id'=>$id))
    ->queryRow();

?v2优化CDbConnectionExt能查看当前使用的主从库配置

Yii::app()->db->setDbName('passport');
//print_r(Yii::app()->getComponent('passport'));

?

?

?