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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!