How to connect multiple database in cakephp

cakephp

In this p.s. I am going to portion useful tip for cakephp Developer, Few days pronounce i have shared tutorial approximately How to merge How to be as soon as to merged database in PHP, MYSQLi & PDO. Here Ill chat not quite the thesame touch in CakePHP, In Big web portal they uses merged database to display data from complex database tables, In cakePHP their is flexibility to combine going on n number of databases easily, Without affection your project code. Its awesome to combat later than n number of databases in single application.

First sensitivity app/Config/database.php file in any code editor. After that locate class DATABASE_CONFIG and grow your adding togethers database configuration.

class DATABASE_CONFIG {
 
	public $default = array(
		'datasource' => 'Database/Mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'username',
		'password' => 'password',
		'database' => 'dbname',
		'prefix' => '',
		//'encoding' => 'utf8',
	);
public $db2 = array(
		'datasource' => 'Database/Mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'username',
		'password' => 'password',
		'database' => 'dbname2',
		'prefix' => '',
		//'encoding' => 'utf8',
	);
public $db3 = array(
		'datasource' => 'Database/Mysql',
		'persistent' => false,
		'host' => 'localhost',
		'login' => 'username',
		'password' => 'password',
		'database' => 'dbname3',
		'prefix' => '',
		//'encoding' => 'utf8',
	);
 
}

The default database is public $default , if you deficiency to use new database(db2, db3) you compulsion to initialize optional late gathering database in your Model using $useDbConfig predefined cakephp method see example.

Calling db2 for model Employee

<?php
App::uses('AppModel', 'Model');
class Employee extends AppModel {
    public $name = 'Employee';
    public $primaryKey = 'id'; 
    public $useDbConfig = 'db2';  
}
?>

Calling db3 for model Company

<?php
App::uses('AppModel', 'Model');
class Company extends AppModel {
    public $name = 'Company';
    public $primaryKey = 'id'; 
    public $useDbConfig = 'db3';  
}
?>

Leave a Reply