学说:让所有孩子成为多对多的关系
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;
}
我需要一个DQL查询,它将返回给定 更新: p>
我正在使用Doctrine 2.1和Symfony 2,我的 实体看起来像这样: p>
的所有
帖子 code> 标记 code>。 p>
posts code>和
tags code>具有多对多关系,给定了tag.slug I 应该能够获得与该标签相关的所有帖子,但是如何? p>
/ **
* @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”)\ n * /
protected $ posts;
}
code> pre>
div>
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} )