多对多+ WHERE字段<>值

时间:2013-06-17 22:22:07

标签: mysql sql symfony doctrine-orm dql

我有关系manyToMany

的“发布”实体
 /**
 * @ORM\ManyToMany(targetEntity="Core\CoreBundle\Entity\User", cascade={"persist", "remove", "merge"})
 * @ORM\JoinTable(name="blogregion_post_views")
 */
protected $views;

 /**
 * @ORM\ManyToMany(targetEntity="Application\BlogRegionBundle\Entity\PostTag", cascade={"persist", "remove", "merge"})
 * @ORM\JoinTable(name="blogregion_tags_match")
 */
protected $tags;

我想获得一个新帖子

    $query = $this->getEm()->createQuery("
        SELECT p FROM BlogRegionBundle:Post p LEFT JOIN p.tags t LEFT JOIN p.views v
        WHERE t.id = :blogId AND p.state = :state AND p.deleted = 0 AND (v <> :user OR v IS NULL )

    ")
        ->setParameter('blogId', $blogId)
        ->setParameter('state', 1)
        ->setParameter('user', $this->getUser())
    ;

但如果我的用户存在“视图”关系

,则返回“发布”

我如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用MEMBER OF条件。

SELECT p FROM BlogRegionBundle:Post p LEFT JOIN p.tags t WHERE t.id = :blogId AND p.state = :state AND p.deleted = 0 AND :user NOT MEMBER OF p.views

来自http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html#dql-select-examples