Reputation: 1522
I am using the Cake for connecting multiple databases in a loop with having same database user config. I just use this method for making different connection on the fly. https://stackoverflow.com/a/6058764/1668476
I just use this in a AppController
function and then in all my controller with
Here is the function to connect with database on the fly:
//Used for connecting different databases on the fly
function dbConnect($database, $dataSource = 'default', $prefix = 'mycake_') {
ClassRegistry::init('ConnectionManager');
$database = $prefix.$database;
$nds = $dataSource . '_' . $database;
$db = ConnectionManager::getDataSource($dataSource);
$db->setConfig(array('name' => $nds, 'database' => $database, 'persistent' => false));
if($ds = ConnectionManager::create($nds, $db->config)) return $db->config;
return false;
}
Then in eevery controller is just use useDbConfig
like:
$newDbConfig = $this->dbConnect($serverConfig);
$this->Summary->useDbConfig = $newDbConfig['name'];
Problem: Problem is when i try to fetch each of the summary table data in foreach loop. Every time it runs it always keep connects with 1st databases only. Here is the loop:
foreach($this->databases as $key=> $database){
$newDbConfig = $this->dbConnect($database);
$this->Summary->useDbConfig = $newDbConfig['name'];
$this->Summary->cacheQueries = false;
$summary = $this->Summary->findAllByPeriod('1');
debug(count($summary));
}
I tried to use clearCache()
or connectionManager:drop()
but with no success.
Please help!
Upvotes: 1
Views: 530
Reputation: 66218
The property useDbConfig
is not the right/best way to change the datasource of an in-use model. To change the data source at run time, call setDataSource, i.e.:
foreach($this->databases as $key=> $database){
$newDbConfig = $this->dbConnect($database);
$this->Summary->setDataSource($newDbConfig['name']);
...
}
Upvotes: 1