我已经配置了 main.php 来处理多个数据库然后 gii 也给出了错误我的 main.php 有以下连接设置
'db'=>array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host='.$dbhost.';dbname='.DATABASENAME,
'emulatePrepare' => true,
'username' => YII_DB_UNAME,
'password' => YII_DB_PASS,
'charset' => 'utf8',
),
'db_transport'=>array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host='.$dbhost.';dbname='.YII_TRANSPORT_DB,
'emulatePrepare' => true,
'username' => YII_DB_UNAME,
'password' => YII_DB_PASS,
'charset' => 'utf8',
),
'db_admission'=>array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host='.$dbhost.';dbname='.YII_ADMISSION_DB,
'emulatePrepare' => true,
'username' => YII_DB_UNAME,
'password' => YII_DB_PASS,
'charset' => 'utf8',
),
'db_extendedsims'=>array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host='.$dbhost.';dbname='.YII_EXTENDEDSIMS_DB,
'emulatePrepare' => true,
'username' => YII_DB_UNAME,
'password' => YII_DB_PASS,
'charset' => 'utf8',
),
现在,当我使用 GII 并在数据库连接中写入“db”(不带引号)时,它会起作用,但如果我写入“db_extendedsims”,它就不起作用。我应该怎么做才能让它适用于所有连接
最佳答案
使用 yii 时使用多个数据库连接的更酷的方法:
'db' => array(
'class' => 'PortalDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=mydb',
'username' => 'dev',
'password' => '123456',
'tablePrefix' => '',
'emulatePrepare' => true,
'enableParamLogging' => true,
'enableProfiling' => true,
'charset' => 'utf8',
),
'dbx' => array(
'connectionString' => 'mysql:host=localhost;dbname=mydb1',
'username' => 'dev',
'password' => '123456',
'charset' => 'utf8',
'tablePrefix' => '',
'autoConnect' => false,
'class' => 'CDbConnection', //this may be the reason you get errors! always set this
),
现在,您模型的 php 代码:
<?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) {
self::$slave_db->active = false;
$config = require(Yii::app()->getBasePath() . '/config/main.php');
//set new connection string; also, you may set the right db user and pass if needed
$connectionString = 'mysql:host=localhost;dbname=mydb' . 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.'));
}
}
并像这样使用它:
public function createDomainSlaveM($model) {
//switch the db connection; $server_id gets values, from 1 to N
DomainSlaveM::$server_id = $model->user_id;
$model_domain_slave_m = new DomainSlaveM();
$model_domain_slave_m->attributes = $model->attributes;
if ($model_domain_slave_m->validate() && $model_domain_slave_m->save()) {
//ok
} else {
//bad
}
}
关于php - 即使配置了多个数据库,也需要有效的数据库连接才能在 yii 中运行此生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19675934/