Reputation: 7686
I need a single DQL query that would return all posts
for a given tag
.
posts
and tags
have a many-to-many relation, s given a tag.slug I should be able to get all posts related to that tag, but how?
UPDATE:
I'm using Doctrine 2.1 with Symfony 2, my entities look like this:
/**
* @ORM\Entity
* @ORM\Table(name="articles__posts")
*/
class ArticlePost
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToMany(targetEntity="ArticleTag", inversedBy="posts")
* @ORM\JoinTable(name="articles__posts_tags")
*/
protected $tags;
}
/**
* @ORM\Entity
* @ORM\Table(name="articles__tags")
* @UniqueEntity(fields="slug")
*/
class ArticleTag
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToMany(targetEntity="ArticlePost", mappedBy="tags")
*/
protected $posts;
}
Upvotes: 1
Views: 816
Reputation: 1544
If you only want to search with one tag, try this:
SELECT post FROM ArticlePost post
JOIN post.tags tag
WHERE tag.slug = {$tagSlug}
If you want to search by more than one tag, simply change the condition to:
... WHERE tag.slug IN ( {$slug1}, {$slug2}, ... {$slugN} )
Upvotes: 1