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).
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$tagis 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.