我试图构建一个小功能,可以在控制器中使用,即时切换数据库,我必须只使用一个数据源.
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->播放器 – > cacheQueries = false;没有更多的成功.
使用它可以正常工作(动态创建新连接):
原文链接:https://www.f2er.com/php/134661.html$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:?,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; }