CakePHP using multiple databases for models

泪湿孤枕 提交于 2019-11-30 21:55:27
Galen

This site has a way to do it, but it's a little hacky.

I've built a site in CakePHP that has models using different databases and I never had problem with joins across different databases - the framework seemed to take care of all that for me. Though you might need to explicitly state the database tables used in your models to get it to work.

To switch the database for the model,

Use the namespace in the controller/model

use Cake\Datasource\ConnectionManager;

In controller;-

$conn = ConnectionManager::get('remote_db_1');
$this->ModelName->connection($conn);

In model:-

$conn = ConnectionManager::get('remote_db_1');
$this->connection($conn);

Note:- If you are saving data for the associated tables too, then keep in mind to change the DB for the associated data otherwise data for the associated table will be inserted into the default connection/DB.

This is the answer for CakePHP 3.*

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!