简体   繁体   English

Symfony学说ManyToMany插入

[英]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. Book和Tag之间的关系是ManyToMany,因为每个Book可以有很多标签,并且每个标签可以依赖于不同的书。 (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? 1)在继续之前,我是否需要先在第1行之后用persist和flush创建书?

2) What is the best way to handle adding (new) tags to books, like I described above ? 2)如上文所述,处理向书籍添加(新)标签的最佳方法是什么?

At the moment when i click on "submit", my local apache does not respond and "hangs up".. 当我单击“提交”时,我的本地apache没有响应并“挂断”。

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. 当然,书籍或标签实体应该具有该方法能够自动添加由教义生成的书籍或标签的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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