我尝试构建一个小型函数,可以在控制器中动态切换数据库,我必须只使用一个数据源。
在我的database.php上:
function __construct() {
$server = Configure::read('Server');
if(!empty($server['database'])) $this->local['database'] = $server['database'];
$this->default = $this->{$server['datasource']};
}
用于根据服务器配置切换数据库。它运作得很好。
我试图建立这个:
/**
* Connects to specified database
*
* @param array $config Server config to use {datasource:?, database:?}
* @return array db->config on success, false on failure
* @access public
*/
function dbConnect($config = array()) {
ClassRegistry::init('ConnectionManager');
//debug($config['datasource']);
//$dbInstance =& ConnectionManager::getInstance();
//$dbInstance->config->{$config['datasource']}['database'] = $config['database'];
$db =& ConnectionManager::getDataSource($config['datasource']);
$db->disconnect();
$db->cacheSources = false;
$db->config['database'] = $config['database'];
$db->config['persistent'] = false;
debug($db->config);
$db->connect();
if(!$db->isConnected()) {
$this->error('!$db->isConnected()');
return false;
}
return $db->config;
}
但遗憾的是,一切似乎都有效,但我可以使用$this->Player->find('list')
从同一个数据库中获取数据。我尝试$this->Player->cacheQueries = false;
但没有取得更多成功。
答案 0 :(得分:8)
使用此功能(即时创建新连接):
$newDbConfig = $this->dbConnect($serverConfig);
$this->Model->useDbConfig = $newDbConfig['name'];
$this->Model->cacheQueries = false;
使用:
/**
* Connects to specified database
*
* @param array $config Server config to use {datasource:?, database:?}
* @return array db->config on success, false on failure
* @access public
*/
function dbConnect($config = array()) {
ClassRegistry::init('ConnectionManager');
$nds = $config['datasource'] . '_' . $config['database'];
$db =& ConnectionManager::getDataSource($config['datasource']);
$db->setConfig(array('name' => $nds, 'database' => $config['database'], 'persistent' => false));
if($ds = ConnectionManager::create($nds, $db->config)) return $db->config;
return false;
}
答案 1 :(得分:4)
我只是想说,现在改变当前模型的数据源(数据库连接)真的很简单:
例如在我的PersonsController索引中:
public function index() {
//change to a different datasource which is already written in App/Config/database.php-file
$this->Person->setDataSource('testdb2');
$persons = $this->Person->find('all');
$this->set('db1persons', $persons);
//change to a different database
$this->Person->setDataSource('testdb');
$persons = $this->Person->find('all');
$this->set('db2persons', $persons);
}
正如您所看到的,这里的关键是使用$ this-> Model-> setDataSource()