我是 Doctrine 的新手,并且很难弄清楚如何在 Symfony2 中使用 Doctrine2 编写下面的查询,这给了我一个用户对象列表作为结果。
查询描述:教师必须获得分配给他作为教师所分配的课程的用户列表
Select * from fos_user_user as user
LEFT JOIN course_assigned_students as cas ON cas.student_id = user.id
WHERE cas.course_id IN
(SELECT cat.course_id from course_assigned_teachers where teachers_id = 1)
GROUP BY user.id
或类似的
Select * from fos_user_user as user
LEFT JOIN course_assigned_students as cas ON cas.student_id = user.id
LEFT JOIN course_assigned_teachers as cat ON cat.course_id = cas.course_id
WHERE cat.teachers_id = 1
GROUP BY user.id
表:
fos_user_user: id
course_assigned_students: student_id, course_id
course_assigned_teachers: teachers_id, course_id
course: id
课程实体
/**
* @var User $teachers
*
* @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User")
* @ORM\JoinTable(name="course_assigned_teachers",
* joinColumns={@ORM\JoinColumn(name="course_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="teachers_id", referencedColumnName="id")}
* )
*/
protected $teachers;
/**
* @var User $students
*
* @ORM\ManyToMany(targetEntity="Application\Sonata\UserBundle\Entity\User")
* @ORM\JoinTable(name="course_assigned_students",
* joinColumns={@ORM\JoinColumn(name="course_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="student_id", referencedColumnName="id")}
* )
*/
protected $students;
我的问题是我不希望我的用户实体引用 Course,因为不是每个应用程序都会使用 CourseBundle。
我是否必须创建代表连接表的 CourseAssignedStudents 和 CourseAssignedTeachers 实体?
所以我可以做类似的事情:
$users = $this->getDoctrine()->getEntityManager()
->createQuery('SELECT user FROM ApplicationSonataUserBundle:User user
LEFT JOIN CourseBundle:CourseAssignedStudents cas WITH cas.student_id = user.id
WHERE cas.course_id IN (SELECT cat.course_id FROM CourseBundle:CourseAssignedTeachers cat where cat.teachers_id = :uid)
GROUP BY user.id')
->setParameter('uid', $this->getUser()->getId())
->execute();