Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

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

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 Symonfy 2 Doctrine. It feels that there should be a very simple way of doing it that I still haven't found.

I have this 2 entities:

class student_main
{
/**
* @ORMManyToMany(targetEntity="support_log", inversedBy="student_main")
* @ORMJoinTable(name="support_log_student")
**/
private $support_log;

and

class support_log
{
/**
* @ORMManyToMany(targetEntity="student_main", mappedBy="support_log")
**/
private $student;

I want to start from support_log. In the controller, in the update action, I have something like that:

if ($editForm->isValid()) {        
  //add the relationship the user added
  foreach($students as $student){
    if(!$em->getRepository('mybundle:student_main')->hasSupportLog($entity,$student)){
        $entity->addstudent_main($student);//*
        }
    }
    $em->persist($entity);
    $em->flush();
    return $this->redirect($this->generateUrl('support_log_edit', array('id' => $id)));
}

Of course, as doctrine Documentation says, I changed that function (addstudent_main) accordingly:

public function addstudent_main(student_main $student)
{
    $student->addsupport_log($this); // the important addition
    $this->student[] = $student;
}

This works fine, my question is more about deleting the relationship. In the form there is a multiselect, and the user might select some students that are already related and some that don't. It feels that there should be an automatic way of doing that, but instead I had to do lots of code.

In the controller, just slightly above the code I wrote before, I put that:

//delete all old relationship
foreach($idsldstudents as $idst){ //I take Id's because the doctrine collection is updating always..
            $stu=$em->getRepository('MyBundle:student_main')->find($idst);
            $stu->deletesupport_log($entity);//I had to create that method (in the entity, I do "$this->support_log->removeElement($support_log)")
            $em->persist($stu);
            $em->flush();
        }

I delete all the relationships of the entity in question (of course, taking in care that is a bidirectional relationship, so it has to be deleted first in the other side), and then the ones that the user selected will be added.

There are other ways of doing that, but I haven't found any simple one. In all of them I have the same problems:

  • I need to check all the time if the relationship exists or not
  • I need to get the old relationships (which is difficult) and compare to the new ones that the user indicated, and delete or create accordingly

Is there a way of doing that that takes care of these 2 problems automatically? (I have a strong feeling that there must be - maybe with a better declaration of the relationship? - that's why I am asking).

Thanks in advance

Edit: My form hasn't anything special, I think I didn't even touch the generated code. It displays the multiselect that I want, the default of Symfony2, where you have to use ctrl key to select more than one. Here is the code:

public function buildForm(FormBuilder $builder, array $options)
{
    $builder           
        ->add('student')
        ... 
        ;
}

The key relies here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...