我们可以使用以下方法将条目保存到数据库中:
$em->persist($entity);
$em->flush();
如何在不使用$this->getEntityManager()->createQuery()
的情况下更新现有条目?
我们能吗?
我正在寻找一种可以更新数据库中现有条目的$em->update()
方式。
做法很简单,Fusselchen 说得对,只需要举个例子就行了
// get entity manager
$em = $this->getDoctrine()->getEntityManager();
// get from this entity manager our "entity" \ object in $item
// also we can get arrayCollection and then do all in foreach loop
$item = $em->getRepository('repoName')->findOneBy($filter);
// change "entity" / object values we want to edit
$item->setSome('someText')
//...
// call to flush that entity manager from which we create $item
$em->flush();
// after that in db column 'some' will have value 'someText'
// btw after call flush we can still use $item as 'selected object' in
// another $em calls and it will have actual (some = 'someText') values
无需额外调用即可更新数据库。EntityManager 会在 flush() 时保持您的模型和数据库同步。
public function updateAction($id)
{
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AppBundle:Product')->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
$product->setName('New product name!');
$em->flush();
return $this->redirectToRoute('homepage');
}