dtgr3392 2013-09-30 20:46
浏览 37
已采纳

如何在使用多个数据库时从从模型创建CActiveDataProvider

I am trying to create a PBBG application. ( where pbbg stands for persistent browser based game )

Because there will be involved multiple servers I want for each server a db.

In order to write data to a slave db, I just save a int value into a static property, like:

    public static function allocate_new_village() {
        VillageSlaveM::$server_id = Yii::app()->session['user_active_world'];//1,2,3,4,5,...
        $model_village_slave_m = new VillageSlaveM();
        $model_village_slave_m->x = 1;
        $model_village_slave_m->y = 1;
        $model_village_slave_m->k = 1;
        $model_village_slave_m->name = 'standard';
        $model_village_slave_m->user_id = 1;
        if ($model_village_slave_m->validate() && $model_village_slave_m->save()) {
//            echo 1;
        } else {
//            echo 2;
        }
    }

The following example, creates a CActivedataProvider by using the main db:

$dataProvider = new CActiveDataProvider('Village');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));

How do I create a CActiveDataProvider by using a slave db and the VillageSlaveM model?

<?php

class VillageSlaveM extends Village {

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public static $server_id = 1;
    public static $master_db;

    public function getDbConnection() {
        //echo __FUNCTION__;
        //die;
        //echo 111;
        self::$master_db = Yii::app()->{"db" . self::$server_id};
        if (self::$master_db instanceof CDbConnection) {
            self::$master_db->setActive(true);
            return self::$master_db;
        }
        else
            throw new CDbException(Yii::t('yii', 'Active Record requires a "db" CDbConnection application component.'));
    }

}
  • 写回答

1条回答 默认 最新

  • douzhang1299 2013-09-30 20:56
    关注

    For some reason, at first it did not worked, now it does:

    VillageSlaveM::$server_id = Yii::app()->session['user_active_world'];
    $dataProvider = new CActiveDataProvider('VillageSlaveM');
    $this->render('index', array(
        'dataProvider' => $dataProvider,
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ios 新安装app收不到fcm推送
  • ¥15 有没有实力的写手?有过成品的优先
  • ¥15 图像信息库的建立与识别
  • ¥15 韩国网站购物,KG支付的支付回调如何解决
  • ¥15 workstation导入ovf文件,报错,怎么解决呢?
  • ¥15 关于#c语言#的问题:构成555单稳态触发器,采用LED指示灯延时时间,对延时时间进行测量并显示(如楼道声控延时灯)需要Proteus仿真图和C语言代码
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
  • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?
  • ¥15 应用商店如何检测在架应用内容是否违规?