Yii 读写分离 分表分库

时间:2022-02-05 19:16:32

本文转自  http://hudeyong926.iteye.com/blog/1299989

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

调用

  1. //AR
  2. class User extends ActiveRecord
  3. {
  4. public $useDbName= 'passport';
  5. //$this->dbWrite();
  6. }
  7. //$connection = $model->getDbConnection();
  8. //DAO
  9. $connection = Yii::app()->db->setDbName('passport');
  10. $count = $connection->createCommand('SELECT COUNT(*) FROM film')->queryScalar();
  11. $sql = 'SELECT film_id,title FROM film';
  12. $dataProvider=new CSqlDataProvider($sql,array(
  13. 'db'=> $connection,
  14. 'totalItemCount'=>$count,
  15. ));
  16. Yii::app()->db->getLastInsertID();
  17. //Query Builder
  18. $user = Yii::app()->db->setDbName('passport')->createCommand()
  19. ->select('id, username, profile')
  20. ->from('tbl_user u')
  21. ->join('tbl_profile p', 'u.id=p.user_id')
  22. ->where('id=:id', array(':id'=>$id))
  23. ->queryRow();

查看当前使用的主从库配置

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

分表AR

  1. public function primaryKey()
  2. {
  3. return 'id';
  4. }
  5. private $tableName = "servicesmsremindrecord";
  6. public function updateMeta($code)
  7. {
  8. $this->tableName = "service_sms_remind_record_".str_pad(($code%100), 2, '0', STR_PAD_LEFT);
  9. $this->refreshMetaData();
  10. return $this;
  11. }
  12. //TestUserDayHealth::model($code)->with('user')->findAll(); 循环放数组