cakephp

Instantiating models from another datasource

Remarks#

There will come a time where your CakePHP application will need to query more than one database. The method for requesting Models from non-default databases is not present in the official documentation.

Instantiating uses App::uses

App::uses('YourModel', 'Model');
$model_1 = new YourModel(array('ds' => 'default'));
$model_2 = new YourModel(array('ds' => 'database2'));

On the fly database changes for modal

For multiple databases, you have the database.php file where you can set as many databases as you need.

If you want to “switch” a database for a specific model on the fly, use the setDataSource() method.

For example, if you have two databases, you can define them in the database.php file as “default” and “sandbox”, as an example.

Then, in your code:

$this->MyModal->setDataSource(‘sandbox’);

The sandbox is the name of the configuration, and the actual name of the database is written only once in the database.php file.


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow