symfony2 / doctrine2中的异常行为

时间:2013-04-25 00:52:27

标签: 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 $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

1 个答案:

答案 0 :(得分:2)

Doctrine Entity Manager 已经在管理此实体(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(),
 );

}