Doctrine 2 : how to clone all values from one object onto another except ID?

标签 doctrine doctrine-orm symfony

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

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

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

我试过“clone”关键字,但没有用。

这是代码。

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

最佳答案

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

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

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

$B = clone $A;
$B->setId(null);

如果您需要担心人际关系,您可能需要 safely implement __clone所以它对相关实体执行您希望它执行的操作。

关于 Doctrine 2 : how to clone all values from one object onto another except ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7533695/

相关文章:

php - Doctrine 分离、缓存和合并

php - MySQL 的 Doctrine 2 配置

php - 我可以在 Doctrine2 中迭代实体的属性吗?

symfony - 用于加入属性的 DQL

forms - 嵌入式表单集合 : The embedded form field won't render

symfony - 在 Symfony 中启用 Twig Debug dump() 的分步指南

php - Doctrine 与 Propel 有很好的比较吗?

php - Doctrine - 从一个表中创建多个实体

php - 如何使用 Doctrine2 中的查询生成器更新多个字段?

php - 如何在 mySQL 数据库中正确存储事件的重复和复杂的提醒?