我正在尝试创建一个PBBG
应用程序。 (其中pbbg代表持久的基于浏览器的游戏)
因为我需要为每个服务器配置多个服务器db。
为了将数据写入从属数据库,我只需将int value
保存到静态属性中,例如:
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;
}
}
以下示例使用主db:
创建CActivedataProvider
$dataProvider = new CActiveDataProvider('Village');
$this->render('index', array(
'dataProvider' => $dataProvider,
));
如何使用从属数据库和CActiveDataProvider
模型创建VillageSlaveM
?
<?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.'));
}
}
答案 0 :(得分:0)
出于某种原因,起初它没有用,现在确实如此:
VillageSlaveM::$server_id = Yii::app()->session['user_active_world'];
$dataProvider = new CActiveDataProvider('VillageSlaveM');
$this->render('index', array(
'dataProvider' => $dataProvider,
));