Question

I am attempting to load a model on the fly using either ClassRegistry::init('ModelName') or loadModel('ModelName') in a controller.

I've got the two databases defined in my database.php config:

Config/database.php

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'username',
    'password' => 'password',
    'database' => 'database1',
    'prefix' => '',
);

public $database2 = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'same_username',
    'password' => 'same_password',
    'database' => 'database2',
    'prefix' => '',
    //'encoding' => 'utf8',
);

Where I am having trouble is properly loading and referencing a table from database2 utilizing Cake's ability to generate a model on the fly. The tables that are stored in database2 do not (and will not) have "ModelName.php" associated with them.

I've tried the following methods:

// Method 1
$this->FirstTable->setDataSource('database2');
ClassRegistry::init('TableFromSecondDatabase')->find('all');
$data = $this->TableFromSecondDatabase->find('all');

// Method 2
$this->loadModel('TableFromSecondDatabase');
$this->TableFromSecondDatabase->find('all');

Both methods give me the following error:

Error: Table TableFromSecondDatabase for model database 2 was not found in datasource default.
Was it helpful?

Solution

You can instantiate the model directly like this:

$model_1 = new Model(array('table' => 'the_table', 'ds' => 'default'));
$model_2 = new Model(array('table' => 'the_table', 'ds' => 'database2'));

Or if you want to create a model for put some logic, you can later instantiate it in the same fashion:

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

OTHER TIPS

in the model that uses the other database:

public $useDbConfig = 'database2';  

It's not necessarily "on the fly", but unless you have the same object in both databases this works fine. If you truly need to connect to multiple databases for the same object, then you should read How to use multiple databases dynamically for one model in CakePHP

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top