Doctrine ORM加入ManyToMany关系

时间:2014-06-22 09:33:28

标签: join orm doctrine-orm

我有用户实体:

class User extends Entity implements UserInterface, ProviderInterface
{

/**
 * @var int
 * @ORM\Id
 * @ORM\Column(name="user_id", type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @var \Doctrine\Common\Collections\Collection
 * @ORM\ManyToMany(targetEntity="Application\Entity\Child", mappedBy="parents")
 */
    protected $children;

...

}

和Child实体:

class Child extends Entity
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(name="child_id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \Application\Entity\Classroom
     *
     * @ORM\ManyToOne(targetEntity="Application\Entity\Classroom")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="classroom_id", referencedColumnName="classroom_id")
     * })
     */
    protected $classroom;

    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="Application\Entity\User", inversedBy="children")
     * @ORM\JoinTable(name="child_parent",
     *      joinColumns={@ORM\JoinColumn(name="child_id", referencedColumnName="child_id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="user_id")}
     * )
     */
    protected $parents;
    ...
}

我需要做的是在UserRepository中添加一个条件,以获取其孩子在教室X中的用户。我还没有看到任何关于为ManyToMany关系创建连接子句的示例。你有什么想法或好的例子吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用DQL查询,我认为这个应该接近你想要的:

SELECT u
FROM Application\Entity\User u
JOIN u.children ch
JOIN c.classroom cr
WHERE cr.id = :classroom
GROUP BY u

希望这有帮助!