多对多关系的 Symfony Doctrine 查询

Symfony Doctrine Query For Many to Many Releationships

我在 Institutes 和 Courses 之间有多对多的关系。我想构建查询 returns 仅列出已分配某些课程的机构。在这种情况下,我已经为 one to many 编写了查询。但不是 many to many。这是关系,

class Institutes { 

     /**
     * @ORM\ManyToMany(targetEntity="Courses", inversedBy="institutes")
     * @ORM\JoinTable(name="institute_courses",
     *      joinColumns={@ORM\JoinColumn(name="institute_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="course_id", referencedColumnName="id")}
     *      )
     */
    protected $courses;
}

class Courses {

    /**
     * @ORM\ManyToMany(targetEntity="Institutes", mappedBy="courses")
     */
    protected $institutes;
}

这是我编写的查询,但没有正常工作。

$repository->createQueryBuilder('s')
                        ->leftJoin('CoursesBundle:Courses','c', 'ON c.institutes = s.courses')
                        ->where('s.active = :active')
                        ->andWhere('s.verified = :active')
                        ->setParameter('active', true)
                        ->orderBy('s.name', 'ASC');

您可以像使用其他类型的关联一样使用 JOIN。以下查询将查找至少分配给一个机构的所有课程:

SELECT c FROM SomeBundle:Courses c JOIN c.institutes i

您可以通过添加连接条件进一步过滤结果:

SELECT c FROM SomeBundle:Courses c JOIN c.institutes i WITH i.something = :someParam

这应该可以解决问题:

$repository->createQueryBuilder('i')
    ->innerJoin('i.courses','c')
    ->where('i.active = TRUE')
    ->andWhere('i.verified = TRUE')
    ->orderBy('i.name', 'ASC');