简体   繁体   English

在CakePHP中使用$ useDbConfig在readOnly数据库和writeOnly数据库之间切换?

[英]Switch between readOnly and writeOnly databases using $useDbConfig in CakePHP?

I have a master and slave database. 我有一个主数据库和从数据库。 To balance some of the load, I want all of my INSERT/UPDATE queries to go to the Master and all of my SELECT queries to go to the slave (since you cannot write to a slave without messing it up). 为了平衡一些负载,我希望所有的INSERT / UPDATE查询都转到主服务器,而所有的SELECT查询都转到从服务器(因为您不能不弄乱它就不能写入从服务器)。 I have the databases defined in the database.php. 我在database.php中定义了数据库。 This is how I am trying to do the switching: 这就是我尝试进行切换的方式:

Inside the AppModel.php beforeFind() , I am setting: 在AppModel.php beforeFind()内部,我正在设置:

$this->useDBConfig = 'readOnly';

Inside the beforeSave() , I am setting: beforeSave()中 ,我正在设置:

$this->useDBConfig = 'writeOnly';

However, after looking deeper I am wondering if the useDBConfig is a one-to-one relationship model-to-database. 但是,在更深入地研究之后,我想知道useDBConfig是否是模型到数据库的一对一关系。 Meaning, maybe useDBConfig is only for pointing a single model to a single database, because this does not always work like I would expect. 这意味着,useDBConfig可能仅用于将单个模型指向单个数据库,因为这并不总是像我期望的那样工作。 Sometimes an INSERT / UPDATE will attempt to run on a readOnly with readOnly permissions and fails. 有时,INSERT / UPDATE会尝试在具有readOnly权限的readOnly上运行,但会失败。

If this is the case, how to I change my CakePHP application to send the requests to the appropriate databases? 如果是这种情况,如何更改CakePHP应用程序以将请求发送到适当的数据库? Should I be doing this a different way? 我应该以其他方式这样做吗?

基本上,您可以覆盖AppModel中的所有保存方法(save,saveField,saveAssociated,saveAll,UpdateAll,delete,deleteAll等),并将父调用封装在两个setDatasource调用之间。

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

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