[英]How to save the data into two databases in CakePHP
In my app/Config/database.php
I have a setup which looks like this, 在我的
app/Config/database.php
我有一个看起来像这样的设置,
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'default_db',
'prefix' => '',
//'encoding' => 'utf8',
);
public $second = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'second_db',
'prefix' => '',
//'encoding' => 'utf8',
);
Now what I wanted was to simultaneously save the data, wherever and whenever I am saving any kind of data. 现在,我想要的是同时保存数据,无论何时何地保存任何类型的数据。 This databases are identical, that is why I want to save the data to both databases to maintain them being identical.
这个数据库是相同的,这就是为什么我想将数据保存到两个数据库以保持它们相同。 Where would I edit such that all the
save/edit/update/delete
processes will both save to both databases. 我将在哪里进行编辑,以便所有
save/edit/update/delete
过程都将保存到两个数据库中。 Thank you in advance. 先感谢您。
EDIT 编辑
in my lib/Cake/Model/Model.php
is a line of code which looks like this 在我的
lib/Cake/Model/Model.php
是一行代码,看起来像这样
/**
* The name of the DataSource connection that this Model uses
*
* The value must be an attribute name that you defined in `app/Config/database.php`
* or created using `ConnectionManager::create()`.
*
* @var string
* @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
*/
public $useDbConfig = 'default';
is there where I should start editing to be able to save the data into two databases? 我应该在哪里开始编辑以将数据保存到两个数据库中? Thanks.
谢谢。
Doing this through CakePHP is slow and not necessary, why aren't you using a feature like DB replication ? 通过CakePHP这样做很慢,而且不是必需的,为什么不使用DB复制之类的功能呢? However, you can change the connection the model us using through the model property useDbConfig .
但是,您可以通过模型属性useDbConfig更改使用我们的模型的连接。
$this->save($data);
$this->useDbConfig = 'second';
$this->save($data, array('callbacks' => false, 'validate' => false);
$this->useDbConfig = 'default';
You could add the last three lines of the above code to your Model::afterSave()
callback, or much better, do it via a behavior and attach it to each model that needs it. 您可以将上述代码的最后三行添加到
Model::afterSave()
回调中,或者更好的方法是通过行为来完成并将其附加到需要它的每个模型上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.