【问题标题】:How to fetch related objects from second many-to-many relation?如何从第二个多对多关系中获取相关对象?
【发布时间】:2015-04-12 20:02:36
【问题描述】:

如果有三个实体:Students、Classes和Topics,它们之间的关系如下:

Student <-> Class: many-to-many(一个学生上多个班级,一个班级有多个学生上)

Class <-> Topic: many-to-many(一个类涉及多个主题,一个主题涉及多个类)

使用 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);
}

【问题讨论】:

    标签: php symfony orm doctrine


    【解决方案1】:

    我想最好的方法是运行单个 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();
    

    【讨论】:

    • 谢谢,一旦我找到了使用您的代码的正确位置并对其进行了一些调整,它就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    相关资源
    最近更新 更多