6

如何使用 symfony2 中的 Doctrine 检查记录是否成功插入数据库?

我在控制器中的操作是

public function createAction(){
    $portfolio = new PmPortfolios();
    $portfolio->setPortfolioName('Umair Portfolio');
    $em = $this->getDoctrine()->getEntityManager();
    $em->persist($portfolio);
    $em->flush();
    if(){
         $this->get('session')->setFlash('my_flash_key',"Record Inserted!");
    }else{
         $this->get('session')->setFlash('my_flash_key',"Record notInserted!");
    }
}

我应该在if声明中写什么?

4

1 回答 1

23

您可以将控制器包装在这样的try / catch块中:

public function createAction() {
    try {
        $portfolio = new PmPortfolios();
        $portfolio->setPortfolioName('Umair Portfolio');
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($portfolio);
        $em->flush();

        $this->get('session')->setFlash('my_flash_key',"Record Inserted!");

    } catch (Exception $e) {
        $this->get('session')->setFlash('my_flash_key',"Record notInserted!");
    }
}

如果插入失败,将抛出异常并捕获。您可能还希望通过调用$e->getMessage()和/或$e->getTraceAsString()解释异常的方式以某种方式在您的 catch 块中记录错误消息。

于 2012-05-28T21:32:52.903 回答