donkey199024 2014-08-04 09:35
浏览 40

如何将数据保存到CakePHP中的两个数据库中

In my app/Config/database.php I have a setup which looks like this,

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. Thank you in advance.

EDIT

in my lib/Cake/Model/Model.php is a line of code which looks like this

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

  • 写回答

1条回答 默认 最新

  • dongle2627 2014-08-04 09:44
    关注

    Doing this through CakePHP is slow and not necessary, why aren't you using a feature like DB replication? However, you can change the connection the model us using through the model property 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.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度