CakePHP using multiple databases for models

南笙酒味 提交于 2019-12-30 07:04:48

问题


Is it possible for certain models to be in one database and other models in another (using the same connection)?

I have a number of read-only tables that I want shared between multiple installations of my system. Other tables need to be per-installation. For the sake of example, let's say users is the shared table, and posts is per-installation.

In one schema (let's call it "shared") we have the users table, and in another schema ("mycake") is posts.

I've been able to get the User model reading from the other database by creating a new database connection which points to the shared database (though the two databases are on the same host and are both accessible with the same login details).

class User extends AppModel {
    var $useDBConfig = 'sharedConnection';
}

The problem is when it comes time to join to the posts table. It doesn't prepend the schema name to the table name, and so it can't find posts.

// what it does
SELECT * FROM users User INNER JOIN posts Post ...

// what I'd like it to do:
SELECT * FROM shared.users User INNER JOIN mycake.posts Post ...

So basically, is there a way to assign a fully qualified table name to a model and force it to use that in all its queries? Setting var $useTable = 'shared.users'; doesn't help...


回答1:


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




回答2:


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.




回答3:


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.*



来源:https://stackoverflow.com/questions/1788072/cakephp-using-multiple-databases-for-models

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