In CakePHP 2, find() would return data from related models in different databases, so long as I had set $useDbConfig appropriately in each Model file. Eg:
class Project extends AppModel {
public $useDbConfig = 'db1';
public $belongsTo = array(
'Client'
);
}
class Client extends AppModel {
public $useDbConfig = 'db2';
}
//in controller:
$this->Project->find('first'); //will get Client data
In CakePHP 3, I've set up my Table Model files with defaultConnectionName(), and in my controller I'm using get() with 'contain' to fetch related models, but one of my related tables is in a different database. Where CakePHP 2 would seemingly issue a separate query to get this data, looks like Cake 3 tries to join the table, and that fails with "Undefined table: relation does not exist."
class ProjectsTable extends Table {
public static function defaultConnectionName() {
return 'db1';
}
public function initialize(array $config){
$this->addAssociations([
'belongsTo' => [
'Clients'
]
]);
}
}
class ClientsTable extends Table {
public static function defaultConnectionName() {
return 'db2';
}
}
//in controller:
$this->Projects->get($id,[
'contain' => [
'Clients'
]
]); //issues error that 'clients' relation does not exist
If I use get() on the related model directly, it works fine - so defaultConnectionName() is good, but does Cake ignore it when the model is being queried as a contained relation? Or how do I need to approach this differently?
EDIT: A solution to my problem came in a later version of CakePHP 3.x: Changing Fetching Strategies. Setting 'strategy' => 'select'
on the association for the other table makes the join work seamlessly again as it did in Cake 2.