简体   繁体   中英

Symfony doctrine ManyToMany insert

I 'm having a form on which i can create a new "Book". For a book, i can add tags (eg to describe additional information about it).

The relation between Book and Tag is ManyToMany, because each Book can have many tags, and each tag can rely to different books. (Each tag is a unique field on its name). So, when a user enters a new tag to a book that does not exists in the database, i want to create the tag when submitting. If it already exists, i want to add the tag to the book. I've tried the following:

$book = $this->form->getData();

foreach ($tags as $tag) {
  $tag = strtolower($tag);

  // check if tag already exists
  $tagEntity = $this->em->getRepository('BookBundle:Tag')->findByName($tag);

  // if not, create new tag and add
  if(null === $tagEntity)
  {
      $tagEntity = new Tag();
      $tagEntity->setName($tag);
  }

  // add tag to book
  $book->addTag($tagEntity);
  // add book to tag
  $tagEntity->addbook($book);

  // create relation between tag and book
  $this->em->persist($book);
  $this->em->persist($tagEntity);

  $this->em->flush();
}

Questions:

1) Do i first need to create the book after line 1 with persist and flush, before i can go on?

2) What is the best way to handle adding (new) tags to books, like I described above ?

At the moment when i click on "submit", my local apache does not respond and "hangs up"..

Regards

Try not adding both book to tag and tag to book. Just add tag to book and persist the book entity. Doctrine should do it all. And of course the book or tag entity should have the method the capable method of adding book or tag which is generated by doctrine automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM