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...
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.*
来源:https://stackoverflow.com/questions/1788072/cakephp-using-multiple-databases-for-models