在symfony中删除外键约束时如何给出错误消息?

时间:2017-07-31 16:49:19

标签: symfony

我有一个图书馆系统,包括学生,书籍和图书馆工作人员。现在,学生ID(pk)被分配给书籍和/或图书馆员工实体。因此,如果用户单击“删除”并且该ID与书籍和/或库人员实体相关联,则用户会收到错误。我尝试过try catch语法,但我想要找到另外一种方法来使用它。我没有尝试过任何其他因为我不知道如何开始这种语法。还有另一种方法可以实现吗?

 public function deleteAction(Request $request, $studentid)
{
    $form = $this->createDeleteForm($studentid);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('comtwclagripayrollBundle:student')->find($studentid);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find student entity.');
        }

        $em->remove($entity);
        $em->flush();

    }


    return $this->redirect($this->generateUrl('student'));
}

目前只是有这个,但它给出了这个错误:  SQLSTATE [23000]:[Microsoft] [SQL Server的ODBC驱动程序11] [SQL Server] DELETE语句与REFERENCE约束冲突。

更新

public function findBystudent($studentbookId, $bookId, $staffId){
    return $this->getEntityManager()
            ->createQuery(
              'select p from comtwclagripayrollBundle:student p
                    where p.studentbookId = :studentbookId AND p.bookId= :bookId or bookId = :studentbookId AND p.staffId= :staffId
                    ')
            ->setParameter('student',$studentId)
            ->setParameter('bookId',$bookId)        
            ->setParameter('staffId',$staffId)  
            ->getResults();

}

 public function deleteAction(Request $request, $studentId)
{
    $form = $this->createDeleteForm($studentId);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('AcmeDemoBundle:student')->findByStudent();

        if ($entity) {
            $this->addFlash('error','ERROR! You cannot delete this Student');
        }

        $em->remove($entity);
        $em->flush();
         $this->addFlash('error','Student Deleted');
    }


    return $this->redirect($this->generateUrl('student'));
}

我创建了这个自定义存储库,如果它找到了这个实体,那么它就不会被删除。但它不起作用。

1 个答案:

答案 0 :(得分:0)

在删除学生之前的删除操作中,您可以检查您是否拥有与他相关联的图书或图书馆,并且只有在没有图书或图书馆存在的情况下才会删除。

public function deleteAction(Request $request, $studentId)
{
...
    $em = $this->getDoctrine()->getManager();
    $deletable = $em->getRepository('AcmeDemoBundle:student')->isDeletable($studentId);

    if (!$deletable) {
        $this->addFlash('error','ERROR! You cannot delete this Student');
    } else {
        $student = $em->getRepository('AcmeDemoBundle:student')->findByStudentId($studentId);
        $em->remove($entity);
        $em->flush();
        $this->addFlash('error','Student Deleted');
    }
    return $this->redirect($this->generateUrl('student'));
}