如何创建一个函数来查询原则2中的实体对象的另一个表


How to create a function that queries another table for an Entity object in Doctrine 2

我有学校和学生实体类。Students实体包含一个属性schoolId,该属性指示学生所属的学校。

在Schools存储库类中,我想创建一个函数,该函数将返回属于该学校的Students对象集合,因此我希望能够像这样调用该函数:

$oSchool->getStudents();

然而,我不确定是否在存储库中拥有函数是最好的地方,因为到目前为止,我遇到的所有示例都是从存储库中调用函数,如下所示:

$aStudents = $em->getRepository(''Entities'Schools')->getStudents();

这似乎不是指当前的schools对象。我假设我必须参考函数内的当前学校对象,我不确定如何做到这一点。目前,我在Schools存储库中的函数是这样的:

public function getStudents()
{
    // get instance of entity manager
    $em = $this->getEntityManager();
    // how do i specify the id of the school object that is calling this function?
    $query = $em->createQuery('SELECT s FROM 'Entities'Students WHERE s.SchoolId = ?'); 
    $aStudents = $query->getResult();
    return $aStudents;
}   

衷心感谢您的帮助。

看一下:实体的元数据映射

特别是User类中的@OneToMany。这与你的师生关系基本相同。

一定要看一下:25.9。不要将外键映射到实体中的字段

只需添加一个$students属性到您的学校实体(使关联双向)。然后调用$yourSchool->getStudents()

见:http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html