2013-02-08 34 views
1

我使用Symfony2.0.18/Doctrine来实现一个功能。Symfony2多对多有独特的表格

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

我创建实体两个“老师”和“学生”和“StudentController.php”。 如果老师不以$ student-> addTeacher($ teacher)退出,那么它工作正常; 但是,如果老师存在,我总是有唯一的错误。

PS:我怎么能保证教师和学生之间的关系被保存?

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

+0

一些代码添加到你的问题,怎么样,你定义在你的实体间关系,并形成 – sonam

+0

检查出这个食谱教程,HTTP:// symfony.com/doc/current/cookbook/form/form_collections.html – sonam

+0

谢谢,我会检查教程。这似乎有点复杂。 – Sifeng

回答

-1

您需要检查,如果教师在学生的实体存在。

在你的学生的实体类方法addTeacher:

public function addTeacher($teacher) 
{ 
    if (!in_array($teacher, $this->teachers->toArray())) { 
     $this->teachers[] = $teacher; 
    } 
} 
+0

谢谢。通过这种方式,我只会得到老师,这些老师与学生相关,而不是全部老师。 – Sifeng

+0

而且师生关系也不会保存。 – Sifeng

0

我知道了!

“表单集合”是不必要的。 有两件事情需要考虑。

  1. 因为老师用户名是独一无二的,它必须首先检查。如果教师的用户名已经存在,只是增加了“addTeacher($ teacherOld)”的关系,如果没有,使用“addTeacher($教师)”
  2. 保存$学生 - > addTeacher($教师)教师与学生之间的关系;

公共职能的addAction(请求$要求){$ 学生= $这个 - >容器 - >获取( '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()));} 

0

只是为了您的信息,你应该总是处理拥有你自己的关系和反侧。其中的逻辑是相当简单的,我提取它的要点在https://gist.github.com/Ocramius/3121916

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

    $this->teachers->add($teacher); 
}