Dynamically change database connection in cakephp 3

只愿长相守 提交于 2019-12-02 07:22:37

Use the ConnectionManager::config() function to create connections on the fly and the ConnnectionManager::alias() method to make all your Table classes use it by default.

There is a very good article describing the process here:

http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database

The only difference is that you can create the connection config on the fly instead of declaring the shards manually as it was shown in that article.

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]);
 
         

Configuring table connections

 namespace App\Model\Table;

 use Cake\ORM\Table;

 class ArticlesTable extends Table
 {
     public static function defaultConnectionName() {
     return 'replica_db';
     }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!