如何在symfony2中使用Doctrine检查记录是否成功插入数据库?
我在 Controller 中的操作是
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
语句应该写什么?
最佳答案
您可以将 Controller 包装在 try/catch
block 中,如下所示:
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 block 中记录错误消息,这将解释异常。
关于php - 检查记录是否成功插入 Symfony2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10790338/