Globally Change the Default Database Connection in CakePHP 2

Written by James McDonald

March 24, 2015

Note: Sadly this doesn’t work in CakePHP 3.x

The secret is define a new database config in the DATABASE_CONFIG class  ( I use “app/Console/cake bake” and the database option )

Edit AppModel.php to specify the $useDbConfig property as the correct connection name as listed in database.php

Warning: Switching from MySQL to Postgres will cause a heap of interesting errors with MySQL specific functions and quoting e.g.

# works for postgres
public $virtualFields = array('name' => "CONCAT(Item.code, ' - ', Item.description)");

# works for mysql but not postgres
public $virtualFields = array('name' => 'CONCAT(Item.code, " - ", Item.description)');
<?php
/**
 * Application model for CakePHP.
 * License snippage
 * app/Model/AppModel.php
*/

App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */
class AppModel extends Model {
    # global database change
    public $useDbConfig = 'postgres';
}


<?php

/* 
 * app/Config/database.php
 *
*/

class DATABASE_CONFIG {

	public $default = array(
		'datasource' => 'Database/Mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'username',
		'password' => 'secretpassword',
		'database' => 'databasename',
	);
	public $postgres = array(
		'datasource' => 'Database/Postgres',
		'persistent' => false,
		'host' => 'localhost',
		'port' => 5432,
		'login' => 'username',
		'password' => 'secretpassword',
		'database' => 'databasename',
	);
}



0 Comments

Trackbacks/Pingbacks

  1. CakePHP 2 – Fix for “Table app_models for model AppModel was not found” Error | The Southern IT Observer - […] Refs: https://jamesmcdonald.id.au/it-tips/globally-change-the-default-database-connection-in-cakephp […]

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…