dongshan1036 2011-10-21 21:43
浏览 34
已采纳

将模型复制到symfony 1.4中的另一个数据库

Using Symfony 1.4 and doctrine I'd like to save a retrieved model to a different database connection:

  1. retrieve model from master-database
  2. change database connection to slave-database
  3. save the model to the slave-database

I have the 2 connections defined in databases.yml. here in pseudo-code:

$model = [retrieved from master-database];
$slaveConnection = Doctrine_Manager::getInstance()
    ->getConnection('slave-connection');
$model->save($slaveConnection);

If I create a new model, $model=new model(); the "code" above successfully saves the model to the slave-connection.

What is going wrong? According to the Symfony log, Symfony recognizes the model as existing and issues an update (instead of an insert).

UPDATE model SET updated_at = '2011-10-21 17:37:32' WHERE id = '1';

Although Symfony is using the correct database connection ('slave-connection'), the update fails because the model isn't present in the slave-database, yet.

And the insert into the slave-database should use all values of the model, not only the changed ones, too.

Anyone can point me to the right direction to save an existing model to a different database?

edit with my solution.

Thanks samura!

Just some additions: After performing deep copy Symfony saved a new id. But I wanted to really clone the model object to the slave db and so, I had to modify the id. That caused unique constraint exceptions, so I had to delete first. So this is it:

$id = $model->getId();
$slaveConnection->execute("delete from modeltable where id=".$id);
$model_copy = $model->copy(true); # deep copy
$model_copy->setId($id);
$model_copy->save($slaveConnection);

hope this helps if someone else stumbles.

  • 写回答

1条回答

  • dongsu3654 2011-10-26 13:09
    关注

    You could use the public function copy($deep = false) method of the Doctrine_Record class.

    $model = [retrieved from master-database];
    $slaveConnection = Doctrine_Manager::getInstance()
      ->getConnection('slave-connection');
    $model_copy = $model->copy(true); # deep copy
    $model_copy->save($slaveConnection);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ROS Turtlebot3 多机协同自主探索环境时遇到的多机任务分配问题,explore节点
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题