Doctrine 2如何将记录添加到没有实体的连接表中?

时间:2011-03-18 21:16:45

标签: doctrine-orm

很难把头缠在这个上面。我有一个Page实体和一个Keyword实体。我在我的Page实体中创建了一个名为$ keywords的成员变量,该变量具有ManyToMany关联,该关联创建一个名为“pages_keywords”的连接表。在我的应用程序中,我希望能够为页面添加关键字。我该如何将该记录添加到数据库中?

我可以访问Page实体的$ keywords成员变量,但我不知道从那里去哪里。我看到ArrayCollection的Doctrine实现有一个add()方法,它只取一个值。我可以直接传递关键字实体的ID并为我创建记录吗?

2 个答案:

答案 0 :(得分:4)

假设您知道要与之关联的实体的主键值(在您的示例中为$ keywordId),最好的方法是获取对实体的引用。这为您提供了参考,而无需对关联实体进行数据库查找。

您在后续答案中发布的解决方案的缺点是需要额外访问数据库才能检索关键字记录。将其作为引用进行检索意味着没有额外的数据库查找:

<?php

// assumes $this->em is already defined as the Doctrine2 EntityManager
$page = $this->em->getRepository('App\Entity\Page')->find($pageId);

// associate $keyword with $page via a reference to the keywordId
$keyword = $this->em->getReference('App\Entity\Keyword', $keywordId);
$page->getKeywords()->add($keyword);
$em->flush();

答案 1 :(得分:1)

出于某种原因,我似乎回答了很多自己的问题。 :)

想出这个。我只是抓住我想要添加到页面的Page对象和关键字对象,然后获取关键字并使用传递关键字对象的add()方法。

// Assuming you have an instance of the Entity Manager
$page = $this->em->getRepository('App\Entity\Page')->find($pageId);
$keyword= $this->em->getRepository('App\Entity\Keyword')->find($keywordId);
$page->getKeywords()->add($keyword);
$em->persist($page);
$em->flush();