So i have my database.php as follows:
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'SOMEHOST',
'port' => 8889,
'login' => 'LOGIN',
'password' => 'PASSWORD',
'database' => 'DB1',
'prefix' => '',
'encoding' => 'utf8',
);
public $db2 = array(
'datasource' => 'Datasources.Freetds',
'persistent' => false,
'host' => 'SOMEHOST',
'port'=> 1433,
'login' => 'LOGIN',
'password' => 'PASSWORD',
'database' => 'DB2',
'prefix' => '',
'encoding' => 'utf8',
);
Then I have some SHELL code which tries to "find" some fields in one DB so that it can cross-check with other fields in the other DB, as follows:
(...)
$qry = $this->Model1->find('all', array(
'fields' => array('Model1.id','Model1.field1'),
'conditions' => array(
'Model1.field2' => 'WAITING'),
'recursive' => -1));
$this->loadModel('Model2');
$num_reg=count($qry);
for ($loop=0; $loop<$num_reg;$loop++) {
$registro = $this->Model2->find("first", array(
'recursive' => -1,
'fields' => array ('Model2.field1', 'Model2.field2'),
'conditions' => array ('Model2.field1' => $qry[$loop]['Model1']['field1'])));
var_dump($registro);
(...)
Model1 uses $default
and Model2 uses $db2
. Model2.php follows (snippet):
public $useTable = 'Table';
public $primaryKey = 'key';
public $useDbConfig = "db2";
Unfortunately, CakePHP doesn't seem to be switching connections and/or DBs, since I get Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Model2.field1' in 'field list'
.
Debugging showed me that CakePHP is trying to use the default DB when building the SQL statement (select ... from DEFAULT.MODEL2TABEL as MODEL2 ....
).
Any ideas?
Thanks in advance!
I went through CakePHP's documentation and failed to understand why this isn't working, but I did find a suitable WORKAROUND, which is documented so I wouldn't rate it as "inelegant". If you don't agree with my answer, please don't "minus-1" me... This solution does work and solves my problem.
I will continue to look for the "right"(best) way and eventually post back here...
Anyway, CakePHP allows you to set your Model's Datasource "on the fly" and that was what ended up working for me.
Just after
$this->loadModel('Model');
place a line like$this->Model->setDatasource('datasource');
and it worked like a charm.This solved my problem in a SHELL, but since the method is under the Model Class, it will probably work in CONTROLLERs as well (http://api.cakephp.org/2.4/class-Model.html#_setDataSource)