1

我正在使用 Symfony2.0.18/Doctrine 来实现一个功能。

有两个表“student”和“teacher”,其中他们的用户名必须是唯一的。它们也是多对多的关系。我想做的是使学生能够添加/删除教师。如果老师已经存在,只需在关系表“student_2_teacher”中插入一个条目。

我为“老师”和“学生”以及“StudentController.php”创建了实体。如果老师没有退出 $student->addTeacher($teacher); ,它工作正常。但是,如果老师存在,我总是会遇到独特的错误。

PS:我怎样才能确保保存教师和学生之间的关系?

有人可以给我一些建议吗?非常感谢!

4

3 回答 3

0

I got it!

"form collections" is unnecessary. There are 2 things, which have to be considered.

  1. because teacher username is unique, it must be checked at first. If teacher username exists already, just add the relationship with "addTeacher($teacherOld)", if not, using "addTeacher($teacher)"
  2. save relationship between teacher and student with $student->addTeacher($teacher);

public function addAction(Request $request) { $student = $this->container->get('security.context')->getToken()->getstudent();

$teacher = new teacher();
$form = $this->createFormBuilder($teacher)
    ->add('teacherUsername', 'text')
    ->getForm();

if($request->getMethod() == 'POST')  {
    $form->bindRequest($request);
    if($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $teacherUsername = $form->get('teacherUsername')->getData();

        // check teacherUsername exist?
        $teacherOld = $this->getDoctrine()->getRepository('PSEMainBundle:teacher')->findOneByTeacherUsername($teacherUsername);
        if ($teacherOld) {
            $student->addTeacher($teacherOld);
        } else {
            $teacher->setTeacherUsername($teacherUsername);
            $student->addTeacher($teacher);
        }

        // add relations
        $em->persist($student);
        $em->flush();

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

return $this->render('PSEMainBundle:teacher:add.html.twig', array('form' => $form->createView()));}

于 2013-02-08T12:35:34.657 回答
0

仅供参考,您应该始终自行处理关系的拥有和反面。逻辑相当简单,我从https://gist.github.com/Ocramius/3121916的要点中提取了它:

public function addTeacher(Teacher $teacher)
{
    if ($this->teachers->contains($teacher)) {
        return;
    }

    $this->teachers->add($teacher);
}
于 2013-02-14T01:49:46.633 回答
-1

您需要检查教师是否存在于学生实体中。

在您的学生实体类方法 addTeacher 中:

public function addTeacher($teacher)
{
    if (!in_array($teacher, $this->teachers->toArray())) {
        $this->teachers[] = $teacher;
    }
}
于 2013-02-08T08:18:36.110 回答