1

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!

1 Answer 1

1

Call setSource

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']);
      ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

which would be best in performance? useDbConfig OR setDataSource ?
Actually i am thinking to change it all over in my controllers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.