如何从第二个多对多关系中获取相关对象?
How to fetch related objects from second many-to-many relation?
如果有三个实体:Students、类和Topics,它们之间的关系如下:
Student <-> Class: many-to-many
(一个学生参加多个 class 课,一个 class 由多个学生参加)
Class <-> Topic: many-to-many
(一个class涵盖多个主题,一个主题涵盖多个classes)
有了 Doctrine,我很容易地实现了 $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,而不是循环每个 class 并获取主题
$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();
如果有三个实体:Students、类和Topics,它们之间的关系如下:
Student <-> Class: many-to-many
(一个学生参加多个 class 课,一个 class 由多个学生参加)
Class <-> Topic: many-to-many
(一个class涵盖多个主题,一个主题涵盖多个classes)
有了 Doctrine,我很容易地实现了 $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,而不是循环每个 class 并获取主题
$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();