具有ManyToMany关系的Doctrine NOT EXIST条件

时间:2017-03-27 07:44:27

标签: sql symfony doctrine-orm

我有两个具有多对多关系的实体:

User 
{
    /**
     * @var Group[]
     *
     * @ORM\ManyToMany(targetEntity="Group", inversedBy="users")
     * @ORM\JoinTable(
     *  name="user_group",
     *  joinColumns={
     *      @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="group_id", referencedColumnName="id")
     *  }
     * )
     */
    protect $groups
}

Group
{
    /**
     * @var User[]
     *
     * @ORM\ManyToMany(targetEntity="User", mappedBy="groups")
     */
    private $users;
}

这会在DB上创建3个表:

  • 用户
  • group
  • USER_GROUP

可以在DQL中操作user_group吗?我正在尝试这样的事情:

SELECT *
FROM user u
WHERE EXISTS
(SELECT ug.user_id FROM user_group ug WHERE ug.user_id = u.id AND ug.group_id = 3)

这不起作用,因为它应该写为实体。我可以使用Native SQL运行它,但我想确保没有更好的解决方案

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

$em = $this->getDoctrine()->getManager(); 
$query = $em->createQueryBuilder('u')
        ->select('u')
        ->from('AppBundle:User', 'u')
        ->innerJoin('u.groups', 'g', 'WITH', 'g.user_id = u.id')

答案 1 :(得分:0)

来自Jonathan Martinez的解决方案有效,但我发现这更直接(特别是因为我也可以使用NOT MEMBER OF):

$query = $em->createQuery('SELECT u.id FROM User u WHERE :groupId MEMBER OF u.groups');
$query->setParameter('groupId', $group);

更多相关信息,请点击此处:

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