我是Doctrine ORM的新手,我正在尝试用Doctrine转换原始SQL查询,以获得实体数组。
基本上,我想获得一个或多个course
实体,其中用户是间接注册的。course
id在traineeship
表中。traineeship
id和user
id在registration
表中。
这是我的SQL查询:
SELECT * FROM course c
LEFT JOIN traineeship t
ON c.id = t.courseId
LEFT JOIN registration r
ON t.id = r.traineeshipId
WHERE r.userId = 2681;
以下是我试图用条令做的:
return $this->createQueryBuilder('c')
->andWhere('t.course = c')
->leftJoin('c.traineeships', 't')
->andWhere('r.traineeship = t')
->leftJoin('t.registrations', 'r')
->andWhere('r.id = :user')
->setParameter('user', $user)
->getQuery()
->execute();
使用我的原始SQL查询,我得到了两个具有给定id的预期结果。使用按原则生成的查询,我只得到一个结果。所以我想我的学说使用不好。
(条令关系:
课程OneToMany培训
实习OneToMany注册
注册ManyToOne用户(
根据原始SQL,我希望得到以下查询:
return $this->createQueryBuilder('c')
->leftJoin('c.traineeships', 't')
->leftJoin('t.registrations', 'r')
->andWhere('r.user = :user')
->setParameter('user', $user)
->getQuery()
->getResult();
请注意,我使用->andWhere('r.user = :user')
而不是->andWhere('r.id = :user')
,因为我假设registration.id
持有注册的id,而不是用户的id。在我的查询中,我进一步假设registration
具有属性user
,该属性保存对用户的引用。
查询应该返回一个课程实体数组。