学说2:如何将除一个对象之外的所有值克隆到另一个对象上?

Too*_*ool 25 doctrine symfony doctrine-orm

在$ 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);
Run Code Online (Sandbox Code Playgroud)

tim*_*dev 38

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

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

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

$B = clone $A;
$B->setId(null);
Run Code Online (Sandbox Code Playgroud)

如果您有关系需要担心,您可能希望安全地实现__clone,以便它能够执行您希望它与相关实体做的事情.

  • 正如DavidLin指出的那样,您不必"取消设置"实体ID(如果该字段已正确标记为ID) (5认同)

Dav*_*Lin 24

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

  • 似乎如果您使用自己的ID生成器,则ID不会设置为null.即使ID字段被标记为ID. (3认同)