简体   繁体   English

CakePHP使用多个数据库作为模型

[英]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. 举例来说,假设users是共享表, posts是按安装的。

In one schema (let's call it "shared") we have the users table, and in another schema ("mycake") is posts . 在一个模式(我们称其为“ shared”)中,有users表,在另一个模式(“ mycake”)中为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. 问题是何时需要加入posts表。 It doesn't prepend the schema name to the table name, and so it can't find posts . 它不会在表名的前面加上模式名,因此无法找到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'; 设置var $useTable = 'shared.users'; doesn't help... 没有帮助...

该网站可以做到这一点,但是有点不客气。

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. 我在CakePHP中建立了一个站点,该站点具有使用不同数据库的模型,而且我对跨不同数据库的联接从未遇到任何问题-该框架似乎为我完成了所有工作。 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. 注意:-如果也要为关联表保存数据,则请记住要更改关联数据的DB,否则关联表的数据将插入到默认连接/数据库中。

This is the answer for CakePHP 3.* 这是CakePHP 3. *的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM