Symfony Doctrine 一对多查询生成器

Symfony Doctrine One to many querybuilder

我在学院和学院课程之间存在一对多关系。

class Institutes {
  /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\OneToMany(targetEntity="PNC\InstitutesBundle\Entity\InstitutesCourses", mappedBy="institute", cascade={"all"})
     * */
    protected $inst;
}

class InstitutesCourses {
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\ManyToOne(targetEntity="PNC\InstitutesBundle\Entity\Institutes", inversedBy="inst")
     * @ORM\JoinColumn(name="institute_id", referencedColumnName="id")
     */
    protected $institute;
    /**
     * @ORM\ManyToOne(targetEntity="PNC\CoursesBundle\Entity\Courses", inversedBy="instituteCourses")
     * @ORM\JoinColumn(name="course_id", referencedColumnName="id")
     */
    protected $course;
}

我想获取分配给一门课程的所有课程。每个研究所都归一个用户所有。我写了这个运行良好的 psql 查询

SELECT ic.*
FROM institutes_courses ic
RIGHT JOIN institutes i ON i.id = ic.institute_id
WHERE i.user_id = 26;

 id  | institute_id | course_id |
-----+--------------+-----------+
 389 |           21 |        51 |
 390 |           21 |        53 |
 391 |           21 |        52 |

并像这样翻译成 doctinre querybuilder;

$repository = $em->getRepository('PNCInstitutesBundle:InstitutesCourses');

            $query= $repository->createQueryBuilder('ic')
                ->select('ic')
                ->from('PNCInstitutesBundle:InstitutesCourses', 'ic')
                ->orderBy('ic.id', 'ASC')
                 // THE FOLLOWING LINE IS CRITICAL:
                ->JOIN('PNCInstitutesBundle:Institutes', 'i', 'WITH' ,'i.id=ic.institute')
                ->where('i.user = :user')
                ->setParameter('user', $this->getUser()->getId())
                ->getQuery();

它说,

[Semantical Error] line 0, col 170 near 'ic INNER JOIN': Error: 'ic' is already defined.

symfony2 新手,不知道哪里出了问题。

如果您查看 createQueryBuilder 的源代码,您将看到以下内容:

public function createQueryBuilder($alias, $indexBy = null)
{
    return $this->_em->createQueryBuilder()
        ->select($alias)
        ->from($this->_entityName, $alias, $indexBy);
}

这意味着您不应在代码中执行以下操作。

->select('ic')
->from('PNCInstitutesBundle:InstitutesCourses', 'ic')

只要去掉那几行就可以了。 Repository 已经为您完成了。

试试这个:

(编辑)

$repository = $em->getRepository('PNCInstitutesBundle:InstitutesCourses');

$query= $repository->createQueryBuilder('ic')
     ->leftJoin('ic.institute', 'i')
     ->where('i.user = :user')
     ->setParameter('user', $this->getUser()->getId())
     ->orderBy('ic.id', 'ASC')
     ->getQuery();

$results = $query->getResult();