Search code examples
phpcakephpcakephp-2.0cakephp-2.1cakephp-2.3

CakePHP - Load model on the fly using a different datasource


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.

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