原则:如何更新对象


Doctrine: how to update an object

我使用2.1原则对于同一条记录,我有两个对象,一个持久化,一个不持久化。我不想重写所有属性,而是想将ID分配给新属性,并调用persist(),希望能更新正确的行。在伪代码中,引导程序看起来像这样:

$old_a = new A(name: "a", value: "old")
$em->persist($old_a);
$em->flush()

现在我在数据库中有一个名为"a"和值"old"的行。我希望有"新"的价值。我可以写

$a = new A(name: "a", value: "new") // create new object
$query = $em->createQuery("SELECT A a WHERE name = 'a'") // check if object with the same name already exists
$old_a = $query->getSingleResult();
$old_a->setValue($a->getValue()) // update value with the new one - here is the problem! If there are many properties I do not want to invoke many times setXXX($a->getXXX). I would like to do something like $old_a = $a or $a->setId($old_a->getId())
$em->persist(old_a) // update the row 

解决方法是创建setId方法并重写id