在Symfony中删除外部约束

时间:2017-07-20 15:09:33

标签: sql-server symfony

如果记录在Symfony中使用添加闪存具有外部约束,如何给出错误。查询可以说,如果外键id为null,则可以删除记录,否则如果它与记录关联则无法删除,如果删除成功则消息。但错误消息未执行。这就是我的尝试:

public function DeleteStudentRecord(){

                $query= $this->getDoctrine()->createQueryBuilder('a')
                ->delete('AcmeDemoBundle: Student','a')
                ->innerJoin('AcmeDemoBundle:Programme','c','WITH','a.c=a')
                ->where('b.studentid IS NULL')
                ->getQuery();
                return $query->getResult();   
            }

public function delete(Request $request, $studentid)
    {

        $form = $this->createDeleteForm($studentid);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $entity = $em->getRepository('AcmeDemoBundle:Student')->DeleteStudentRecord();

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

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

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

更改

public function delete(Request $request, $studentid)
{

    $form = $this->createDeleteForm($studentid);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AcmeDemoBundle:Student')->DeleteStudentRecord();

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

        $this->addFlash('success','Successfully delete student record');

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

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

但这并不能产生正确的结果,或者说不正确。

1 个答案:

答案 0 :(得分:1)

您可能需要更多一点来检查实体是否存在,然后是否可以删除。

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

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AcmeDemoBundle:Student')
            ->findBy('studentId', $studentid);

        if (!$entity) {
             $this->addFlash('error',
                'ERROR! Student Record with id: ' . $studentid . ' doesn\'t exist.'
             );
             return $this->redirect($this->generateUrl('student'));
        }

        try {
            $em->remove($entity);
            $em->flush();
        // Catch the Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException
        } catch(ForeignKeyConstraintViolationException $e) {
            $this->addFlash('error',
                '//Whatever message you want here'
            );

            // Whatever action you want from here.....
        }
    }
}