Dynamically change database connection in cakephp 3

后端 未结 3 1060
耶瑟儿~
耶瑟儿~ 2021-01-24 02:36

I\'m trying to change the database connection used in cakephp 3 on the fly. Every answer to this question that I found refers to cakephp 2 (The

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-24 03:32

    Change database connection for one model:

    In app.php :

    'test' => [
                'className' => 'Cake\Database\Connection',
                'driver' => 'Cake\Database\Driver\Mysql',
                'persistent' => false,
                'host' => MySQL_HOST,
                //'port' => 'nonstandard_port_number',
                'port' => MySQL_PORT,
                'username' => MySQL_USER,
                'password' => MySQL_PASS,
                'database' => 'test',
                'encoding' => 'utf8',
                'timezone' => 'UTC',
                'cacheMetadata' => true,
                'quoteIdentifiers' => false,
                'log' => false,
            //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
            ]

    In Controller :

    $conn = ConnectionManager::get('test');
     $_model = TableRegistry::get('your_alias', ['table' => 'your_table', 'connection' => $conn]);
     
             

提交回复
热议问题