检查该记录是否已成功插入Symfony2

时间:2012-05-28 20:56:05

标签: php symfony doctrine-orm

如何在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声明中写什么?

1 个答案:

答案 0 :(得分: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块中记录错误消息。