【问题标题】:Doctrine 2: how to clone all values from one object onto another except ID?教义 2:如何将一个对象的所有值克隆到另一个对象上,除了 ID?
【发布时间】:2011-09-23 19:10:36
【问题描述】:

在 $entity 变量中,有一个与 $other_address 相同类型的对象,但所有字段值都被填写。

我想将 $other_address 对象中的所有字段设置为与 $entity 对象具有完全相同的值。

这在少于 N 行中是否可行,其中 N 是我需要设置的字段数?

我尝试了“克隆”关键字,但没有成功。

这是代码。

                $other_address = $em->getRepository('PennyHomeBundle:Address')
          ->findBy(array('user' => $this->get('security.context')->getToken()->getUser()->getId(), 'type' => $check_type));
                $other_address = $other_address[0];


                //I want to set all values in this object to have values from another object of same type
                $other_address->setName($entity->getName());
                $other_address->setAddress1($entity->getAddress1());
                $other_address->setAddress2($entity->getAddress2());
                $other_address->setSuburbTown($entity->getSuburbTown());
                $other_address->setCityState($entity->getCityState());
                $other_address->setPostZipCode($entity->getPostZipCode());
                $other_address->setPhone($entity->getPhone());
                $other_address->setType($check_type);

【问题讨论】:

    标签: doctrine doctrine-orm symfony


    【解决方案1】:

    我不确定为什么克隆不起作用。

    这似乎对我有用,至少在一个基本的测试用例中:

    $A = $em->find('Some\Entity',1);
    
    $B = clone $A;
    $B->setId(null);
    

    如果您需要担心关系,您可能需要safely implement __clone,这样它就可以完成您希望它对相关实体执行的操作。

    【讨论】:

    • 正如 DavidLin 指出的那样,您不必“取消设置”实体 ID(如果该字段被正确标记为 ID)
    • 嗨@timdev,如果我想复制,假设我有一个临时对象,我需要将它合并到原始对象中?这可能吗?
    【解决方案2】:

    只需克隆实体,您甚至不需要取消设置 id。 Doctrine 已经为你解决了这个问题

    【讨论】:

    • 看来,如果您使用自己的 ID 生成器,则 ID 未设置为 null。即使 ID 字段被标记为 ID。
    【解决方案3】:
    $A = $em->find('Some\Entity',1);
    
    $B = clone $A;
    $em->persist($B);
    $em->flush();
    

    如果你merge 它会更新实体,最好使用persist() 它会复制整行并添加自动递增的主键

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      相关资源
      最近更新 更多