문제

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.
도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top