Proper way to update bidirectional Many to Many relationship symfony2-doctrine

前端 未结 4 1002
庸人自扰
庸人自扰 2020-12-10 20:35

I did some research, and after reading this and this (and all the related questions) I still can\'t figure which is the proper way to update a many to many relationship in S

4条回答
  •  被撕碎了的回忆
    2020-12-10 20:44

    So far, (and to avoid having a question unanswered forever), it looks like there is no "simple way that I still haven't found" to do that. That would be the answer to my question, according to the comments.

    But the code can be improved and make it more elegant thanks to the improvements of last comment. If at entity level we have that: gist.github.com/3121916 (from the comment)

    Then, the code in the controller can be reduced a little bit:

    $editForm->bindRequest($request);
      if ($editForm->isValid()) { 
      //delete all old relationships, we can go from student:    
      foreach($em->getRepository('mybundle:student_main')->findAll() as $oldstudent)
      {
         $oldstudent->removeSupportLog($entity);
         //if they are related, the relationship will be deleted. 
         //(check the code from the url)  
      }  
      //add the relationship the user added in the widget
      $students=$entity->getStudent();
      foreach($students as $student) 
      {
         $entity->addstudent_main($student);
      }
      $em->persist($entity);
      $em->flush();
      return $this->redirect($this->generateUrl('support_log_edit', array('id' => $id)));
    }
    

    It is still not the "magical" symfony solution I expected, but so far the best I can do (maybe group this code inside a function in the repository, to make it more elegant).

    If you have better ideas, I'm all ears.

提交回复
热议问题