如何从二次多对多关系中提取相关对象


How to fetch related objects from second many-to-many relation?

如果有三个实体:学生、课程和主题,它们之间的关系如下:

Student <-> Class: many-to-many(一个学生参加多个课程,一个课程有多个学生参加)

Class <-> Topic: many-to-many(一个类包含多个主题,一个主题包含在多个类中)

有了条令,我很容易地实现了$student->getClasses()$class->getTopics()

实现$student->getTopics()的最佳方式是什么?

以下工作,但似乎不是正确

public function getTopics()
{
    $topics = array();
    foreach ($student->getClasses() as $class) {
        $topics = array_merge($topics, $class->getTopics());
    }
    return array_unique($topics);
}

我想最好的方法是运行单个DQL,而不是循环每个类并获取主题

$DM = $this->getDoctrine()->getManager();
$query = $DM->createQueryBuilder('t')
    ->select('t')
    ->from('NamespaceYourBundle:Topic', 't')
    ->innerJoin('t.class','c')
    ->innerJoin('c.student','s')
    ->where('s.id = :id')
    ->setParameter(':id',$student_id)
    ->getQuery();
$topics= $query->getResult();