0

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.

Community
  • 1
  • 1
user4838338
  • 83
  • 1
  • 5
  • I think I solved my own problem, so leaving this here for future generations: Turns out, I didn't have autoload enabled in bootstrap.php I had: Plugin::load('Importer', [ 'bootstrap' => false, 'routes' => true]); instead of: Plugin::load('Importer', ['autoload' => true, 'bootstrap' => false, 'routes' => true]); – user4838338 Oct 03 '16 at 23:11
  • http://book.cakephp.org/3.0/en/plugins.html#autoloading-plugin-classes – ndm Oct 04 '16 at 01:22

0 Answers0