CakePHP switch database (using same datasource) on the fly?

谁说胖子不能爱 提交于 2019-11-27 13:48:34

Made it work using this (create a new connection on the fly) :

$newDbConfig = $this->dbConnect($serverConfig);
$this->Model->useDbConfig = $newDbConfig['name'];
$this->Model->cacheQueries = false;

With :

/**
 * 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;

}

I just wanted to tell that nowadays it's really simple to change current model's datasource (database connection):

For example in my PersonsController index:

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);
}

As you can see the key here is to use $this->Model->setDataSource()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!