【问题标题】:Symfony Doctrine Query For Many to Many ReleationshipsSymfony Doctrine 查询多对多关系
【发布时间】:2016-07-04 12:28:23
【问题描述】:

Institutes 和 Courses 之间存在多对多关系。我想构建只返回分配了一些课程的机构列表的查询。在这种情况下,我已经为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');

【问题讨论】:

  • 如果您想确保只针对有课程的机构,请尝试用 innerJoin 替换 leftJoin

标签: php symfony doctrine-orm many-to-many query-builder


【解决方案1】:

这应该可以解决问题:

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

【讨论】:

  • 不,不会返回所有机构
【解决方案2】:

您可以像处理其他类型的关联一样使用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

【讨论】:

  • 嗯。错过了。然后相应地更改查询。我已经向您展示了如何做到这一点。
猜你喜欢
  • 1970-01-01
  • 2014-12-20
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多