dongyuan7981 2015-11-04 08:18
浏览 41
已采纳

symfony doctrine将实体对象移动到另一个实体类型

Is there any way to move a row to another mysql table with Doctrine?

I am searching for the equivalent of the following mysql:

INSERT myTableCopy (
   SELECT * FROM myTable WHERE id = 2
)

I expect something like this:

// $first is an object from  myTable
$this->getDoctrine()->getRepository('MyBundle:MyTable')->findOneBy(array('id' => 2));
$second = new myTableCopy();
$second = clone $first;

Unfortunately (but logically), the $second entity is of type myTable...

How can I do this?

I know I can use prepare statement, but I want to know if I can do this with one of the Doctrine function.

FYI: I have a huge table (several millions of rows), and I want to move old data to a "backup table" that would not be so used

PS: I know that this thread is proposing the following solution, but I think that there should be a better way with serializer/normalizer...

 // now loop over the properties of each post array...
    foreach ($post as $property => $value) {
        // create a setter
        $method = sprintf('set%s', ucwords($property)); // or you can cheat and omit ucwords() because PHP method calls are case insensitive
        // use the method as a variable variable to set your value
        $post->$method($value);
    }
  • 写回答

2条回答 默认 最新

  • donglun7151 2015-11-04 10:24
    关注

    I finally found the error after reading this post from @Colin M.

    Here is the final solution of my problem:

    $myOriginalObject = $this->getDoctrine()->getRepository('MyBundle:MyTable')->findOneBy(array('id' => 2));
    // Here modify the original object if needed...
    
    $myTableCopyObject = new myTableCopy();
    
    $oldReflection = new \ReflectionObject($myOriginalObject);
    $newReflection = new \ReflectionObject($myTableCopyObject);
    
    foreach ($oldReflection->getProperties() as $property) {
        if ($newReflection->hasProperty($property->getName())) {
            $newProperty = $newReflection->getProperty($property->getName());
            $newProperty->setAccessible(true);
            $property->setAccessible(true);
            $newProperty->setValue($myTableCopyObject, $property->getValue($doi_tmp));
        }
    }               
    
    $this->em->persist($myTableCopyObject);
    $this->em->remove($myOriginalObject);
    $this->em->flush();
    

    NB: only the ID seem to not be conserved when you have an auto-increment ID

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题