Saturday, April 27, 2013

How to use multiple databases dynamically for one model in CakePHP

I put in the app/Controller/AppModel.php

class AppModel extends Model
{
  /**
   * Connects to specified database
   *
   * @param String name of different database to connect with.
   * @param String name of existing datasource
   * @return boolean true on success, false on failure
   * @access public
   */
    public function setDatabase($database, $datasource = 'default')
    {
      $nds = $datasource . '_' . $database;      
      $db  = &ConnectionManager::getDataSource($datasource);

      $db->setConfig(array(
        'name'       => $nds,
        'database'   => $database,
        'persistent' => false
      ));

      if ( $ds = ConnectionManager::create($nds, $db->config) ) {
        $this->useDbConfig  = $nds;
        $this->cacheQueries = false;
        return true;
      }

      return false;
    }
}

And here is how I used it in my app/Controller/CarsController.php:
class CarsController extends AppController
{
  public function index()
  {
    $this->Car->setDatabase('cake_sandbox_client3');
 
    or you can directly use:
    $this->Car->setDataSource('test1'); 
    /* data source name from cofig/database.php */

    $cars = $this->Car->find('all');

    $this->set('cars', $cars);
  }

}

http://stackoverflow.com/questions/13223946/how-to-use-multiple-databases-dynamically-for-one-model-in-cakephp

No comments:

Post a Comment