Doctrine:如何更新对象

时间:2011-11-01 14:55:00

标签: php doctrine-orm

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

$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 

1 个答案:

答案 0 :(得分:0)

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