phpmysqlcakephpcakephp-model

CakePHP using multiple databases for models


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


Solution

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