Yii 读写分离 分表分库
本文转自 http://hudeyong926.iteye.com/blog/1299989
实现一主一从,一主多从,多主多从的读写分离 。支持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();
查看当前使用的主从库配置
- Yii::app()->db->setDbName('passport');
- //print_r(Yii::app()->getComponent('passport'));
分表AR
- public function primaryKey()
- {
- return 'id';
- }
- private $tableName = "servicesmsremindrecord";
- public function updateMeta($code)
- {
- $this->tableName = "service_sms_remind_record_".str_pad(($code%100), 2, '0', STR_PAD_LEFT);
- $this->refreshMetaData();
- return $this;
- }
- //TestUserDayHealth::model($code)->with('user')->findAll(); 循环放数组