如何使用 DQL 在 Symfony2 中计算多对多关系
我想计算特定文章的标签数量。我有两个实体(文章、标签),它们通过多对多关联相关:
//Bundle/Entity/Article.php
/**
* @ORM\ManyToMany(targetEntity="Tag")
*/
private $tags;
现在我有 n 篇带有 m 个标签的文章,我想知道特定标签的使用频率。
我对 Symfony2 和 Doctrine 都比较陌生。问题是我不知道在哪里适合这样的查询(我猜它应该驻留在 ArticleRepository 中,但另一方面,将它放在 TagRepository 中是有意义的)以及如何加入正确的表(在这个案例文章、文章标签、标签)。
I would like to count the number of tags given a specific article. I've got two entities (Article, Tag) which are related by a many-to-many association:
//Bundle/Entity/Article.php
/**
* @ORM\ManyToMany(targetEntity="Tag")
*/
private $tags;
Now I've got n articles with m tags and I would like to know how often a specific tag has been used.
I'm relatively new to both Symfony2 and Doctrine. The problem is that I don't know where to fit such a query (I guess it should reside in the ArticleRepository but on the other hand it would make sense to have it in the TagRepository) and how to JOIN the correct tables (in this case Article, article_tag, Tag).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我能想到的最简单的方法是在 Article 和 Tag 之间建立双向关系:
然后你可以(假设你已经设置了标准的 getter 和 setter)使用
$tag->getArticles()-> ;count();
,其中$tag
是托管标签实体,用于获取附加到该标签的文章数量。这是有效的,因为在填充 ToMany 关系属性时,Doctrine 使用Doctrine\Common\Collections\ArrayCollection
的实例。在此处查看源代码。另外,如果您走这条路,请确保阅读有关选择拥有方和反方的文档 此处。
The simplest way that I can think of is to just set up a bidirectional relationship between Article and Tag:
Then you can (assuming you've set up standard getters and setters) use
$tag->getArticles()->count();
, where$tag
is a managed Tag entity, to get the number of articles attached to that tag. This works because when populating ToMany relationship properties, Doctrine uses an instance ofDoctrine\Common\Collections\ArrayCollection
. Check out the source here.Also, if you go this route, make sure you read the documentation on picking an owning and inverse side here.
您可以使用特定文章来计算标签数量。假设文章 id = 5:
这给出了文章实体中仅适用于文章 id = 5 的标签数量。
You can count the number of tags by using a specific article..lets say article id=5:
This gives me the number of tags in Article Entity only for article id = 5.