我需要在应用运行时编辑dbx
连接。
我已经定义了2个数据库连接设置;
db
用于中央数据库
dbx
用于任何其他从属数据库(我的应用程序为每个用户都有一个从属数据库)
对于每个用户,dbx
都有自己的用户名和密码,将保存在db表中;
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=dvc',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
'dbx' => array(
'connectionString' => 'mysql:host=localhost;dbname=dvc2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => '',
'class' => 'CDbConnection' // DO NOT FORGET THIS!
),
答案 0 :(得分:1)
我认为,您可能无法在配置上配置dbx
,并且在用户登录之后使用所需的参数创建组件之前,在代码中使用dbx之前。你可以通过(描述here):
Yii::app()->createComponent('dbx', array( 'connectionString' => 'mysql:host=localhost;dbname=dvc2', 'username' => <user db login>, 'password' => <user db pass>, 'charset' => 'utf8', 'tablePrefix' => '', 'class' => 'CDbConnection' // DO NOT FORGET THIS! ))
要删除现有组件,您可以执行Yii::app()->createComponent('dbx', null)
,然后使用其他参数创建此组件
答案 1 :(得分:0)
所以,测试的解决方案是:
<?php
class DomainSlaveM extends Domain {
public static function model($className = __CLASS__) {
return parent::model($className);
}
public static $server_id = 1;
public static $slave_db;
public function getDbConnection() {
self::$slave_db = Yii::app()->dbx;
if (self::$slave_db instanceof CDbConnection) {
$config = require(Yii::app()->getBasePath() . '/config/location/setting.php');
$connectionString = 'mysql:host=localhost;dbname=irdb' . self::$server_id;
self::$slave_db->connectionString = sprintf($connectionString, 'dbx');
self::$slave_db->setActive(true);
return self::$slave_db;
}
else
throw new CDbException(Yii::t('yii', 'Active Record requires a "db" CDbConnection application component.'));
}
}
,代码是:
DomainSlaveM::$server_id = 1;
$model_domain_slave_m = DomainSlaveM::model()->findByAttributes(array('id' => 1));
if ($model_domain_slave_m) {
$model_domain_slave_m->updated = time();
if ($model_domain_slave_m->validate() && $model_domain_slave_m->save()) {
}
}
原始文章发现于:click here