Doctrine 2:如何将所有值从一个对象克隆到另一个除ID之外? [英] Doctrine 2: how to clone all values from one object onto another except ID?

查看:117
本文介绍了Doctrine 2:如何将所有值从一个对象克隆到另一个除ID之外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在$实体变量中,有一个与$ other_address相同类型的对象,但填入所有字段值。 other_address对象具有与$ entity对象完全相同的值。



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

我尝试过克隆关键字,但没有起作用。



这是代码。

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


//我想将此对象中的所有值设置为具有相同类型的另一个对象的值
$ 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);


解决方案

我不知道为什么克隆不会工作



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

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

$ B =克隆$ A;
$ B-> setId(null);

如果您有担心的关系,您可能希望安全地实现__clone ,所以它做你想要的与相关实体有关。


In $entity variable, there is an object of same type as $other_address, but with all field values filled in.

I want to set all fields in $other_address object to have exact same values as $entity object.

Is this doable in less then N number of lines, where N is number of fields I need to set?

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);

解决方案

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.

这篇关于Doctrine 2:如何将所有值从一个对象克隆到另一个除ID之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆