In $entity variable, there is an object of same type as $other_address, but with all field values filled in.
在$ entity变量中,有一个与$ other_address类型相同的对象,但填写了所有字段值。
I want to set all fields in $other_address object to have exact same values as $entity object.
我想将$ other_address对象中的所有字段设置为与$ entity对象具有完全相同的值。
Is this doable in less then N number of lines, where N is number of fields I need to set?
这是否可以少于N行,其中N是我需要设置的字段数?
I tried "clone" keyword, but it didnt work.
我尝试过“克隆”关键字,但它没有用。
Here's the code.
这是代码。
$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);
3 个解决方案
#1
38
I'm not sure why cloning won't work.
我不确定为什么克隆不起作用。
This seems to work for me, at least in a basic test case:
这似乎对我有用,至少在一个基本的测试用例中:
$A = $em->find('Some\Entity',1);
$B = clone $A;
$B->setId(null);
If you've got relationships to worry about, you might want to safely implement __clone so it does what you want it to do with related entities.
如果您有关系需要担心,您可能需要安全地实现__clone,以便它能够执行您希望它与相关实体做的事情。
#2
23
Just Clone the entity, you don't even need to unset the id. Doctrine has tackled this for you
只需克隆实体,您甚至不需要取消设置ID。 Doctrine为你解决了这个问题
#3
0
$A = $em->find('Some\Entity',1);
$B = clone $A;
$em->persist($B);
$em->flush();
if you merge
it will update the entity, best you use persist()
it will duplicate the entire row and add auto incremented primary key
如果你合并它将更新实体,最好你使用persist()它将复制整行并添加自动递增的主键
#1
38
I'm not sure why cloning won't work.
我不确定为什么克隆不起作用。
This seems to work for me, at least in a basic test case:
这似乎对我有用,至少在一个基本的测试用例中:
$A = $em->find('Some\Entity',1);
$B = clone $A;
$B->setId(null);
If you've got relationships to worry about, you might want to safely implement __clone so it does what you want it to do with related entities.
如果您有关系需要担心,您可能需要安全地实现__clone,以便它能够执行您希望它与相关实体做的事情。
#2
23
Just Clone the entity, you don't even need to unset the id. Doctrine has tackled this for you
只需克隆实体,您甚至不需要取消设置ID。 Doctrine为你解决了这个问题
#3
0
$A = $em->find('Some\Entity',1);
$B = clone $A;
$em->persist($B);
$em->flush();
if you merge
it will update the entity, best you use persist()
it will duplicate the entire row and add auto incremented primary key
如果你合并它将更新实体,最好你使用persist()它将复制整行并添加自动递增的主键