Php symfony2/doctrine2中的异常行为
我有以下问题: 在将对象保存到数据库之前,我要检查一些内容: 这里是我的控制器:Php symfony2/doctrine2中的异常行为,php,symfony,doctrine-orm,Php,Symfony,Doctrine Orm,我有以下问题: 在将对象保存到数据库之前,我要检查一些内容: 这里是我的控制器: /** * Edits an existing Document entity. * * @Route("/{id}", name="document_update") * @Method("PUT") * @Template("ControlBundle:Document:edit.html.twig") */ public function updateAction(Request $reques
/**
* Edits an existing Document entity.
*
* @Route("/{id}", name="document_update")
* @Method("PUT")
* @Template("ControlBundle:Document:edit.html.twig")
*/
public function updateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ControlBundle:Document')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Document entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new DocumentType(), $entity);
$editForm->bind($request);
if ($editForm->isValid()) {
$document = $em->getRepository('ControlBundle:Document')->findOneBy(array(
'id' => $id,
));
if ($document->getCount() > 100)
$em->flush();
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
在我的数据库中,我有:
id count .......
23 110
在我的表格中,我编辑:
id count .......
23 34
但当我这么做的时候:
$document = $em->getRepository('ControlBundle:Document')->findOneBy(array(
'id' => $id,
));
//here $document->getCount() return 34; ------WHY? should return 110!!!
if ($document->getCount() > 100)
$em->flush();
致以最良好的祝愿:D条令实体管理器已经在管理该实体(ID=23的文档),并且它不会第二次从数据库重新加载数据,它只使用它已经管理的实体,其计数值已替换为表单中的34 试试这个:
/**
* Edits an existing Document entity.
*
* @Route("/{id}", name="document_update")
* @Method("PUT")
* @Template("ControlBundle:Document:edit.html.twig")
*/
public function updateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ControlBundle:Document')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Document entity.');
}
$lastCountValue = $entity->getCount();
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new DocumentType(), $entity);
$editForm->bind($request);
if ($editForm->isValid() && lastCountValue > 100) {
$em->flush();
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}首先绑定请求中的
$document
,然后用数据库中尚未保存的值覆盖它。而且它还没有被持久化,因为此时您没有刷新它。我不明白为什么要覆盖$document
,应该删除这一行$document=$em->getRepository('ControlBundle:document')->findOneBy(数组('id'=>$id,)代码>然后应该可以工作。