通常的方式to update an entity是这样的:
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AppBundle:Product')->find($id);
$product->setName("New product name!");
$em->flush();
不需要调用persist():因为你从Doctrine中获取了$ product对象,所以它已经被管理了。
但是:如果获取实体然后将其传递给更新函数,如下所示:
// Somewhere in the application I get the Product entity, call a setter, and want to save the Entity:
$product->setName("A new name!");
$productService->update($product);
// Inside productService:
function update(Product $product) {
// what to do here to update the entity? Is it still managed?
$em = $this->getEntityManager();
$em->persist($product);
$em->flush();
}
如果它仍然被管理,则不需要调用persist(),但是它是什么?更新(..)中的代码似乎确实有效,但这是正确的方法吗?