I am trying to load some data from a plugin model which uses a different database. I have added an entry in my config/app.php as follows:
/**
* The test connection is used during the test suite.
*/
'alternate1' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
//'port' => 'non_standard_port_number',
'username' => 'alt_user',
'password' => '********',
'database' => 'secondary_db',
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
'url' => env('DATABASE_TEST_URL', null),
],
In my plugin /plugins/Importer/src/Model/LogsTable.php class, I've added
public static function defaultConnectionName() {
return 'alternate1';
}
Now, I'd like to be able to access this data from my main applications controllers, so I tried this:
in /src/Controllers/ReviewController.php
$this->loadModel('Importer.Logs');
$logCount = $this->Logs->find('all')->count();
If I check the model like this:
print_r($this->Logs);
I see that it is still using the 'default' connection, and not the 'alternate1' connection.
Cake\ORM\Table Object ( [registryAlias] => Importer.Logs [table] => logs [alias] => Logs [entityClass] => \Cake\ORM\Entity [associations] => Array ( ) [behaviors] => Array ( ) [defaultConnection] => default [connectionName] => default )
I have also tried TableRegistry::get('Importer.Logs') and a few other variations, but in the end I am unable to get Cake to properly load the correct data connection.
I'm missing something simple here, I just know it. This answer: CakePHP 3 defaultConnectionName in plugin model doesn't work seems to be what I want, but it's not correct. I'm already using the Namespace.Model format.