简体   繁体   English

如何创建一个 function 查询另一个表以获取 Doctrine 2

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

I have Schools and Students entity classes.我有 Schools 和 Students 实体类。 Students entity contains a property schoolId that indicates the school a student belongs to.学生实体包含一个属性 schoolId,指示学生所属的学校。

Within a Schools repository class I want to create a function that will return a collection of Students objects that belong to that school so I want to be able to call the function like this:在学校存储库 class 中,我想创建一个 function ,它将返回属于该学校的学生对象的集合,因此我希望能够像这样调用 ZC1C425268E68385D1AB5074C17A94F14

$oSchool->getStudents();

However I'm not sure if having the function in the repository is the best place because so far all the examples I've come accross call the function from the repository like this:但是我不确定存储库中是否有 function 是最好的地方,因为到目前为止,我遇到的所有示例都从存储库中调用 function,如下所示:

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

This doesn't seem to refer to the current schools object.这个好像不是指现在的学校object。 I'm assuming I would have to refer to the current schools object within the function, I am not sure how to do this.我假设我必须参考 function 内的当前学校 object,我不知道该怎么做。 Currently this is what my function in the Schools repository looks like:目前这是我在 Schools 存储库中的 function 的样子:

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;
}   

Sincerely appreciate any help.真诚感谢任何帮助。

just add an $students attribute to your school-entity (making the association bidirectional).只需将$students属性添加到您的学校实体(使关联双向)。 Then you can just call $yourSchool->getStudents()然后你可以调用$yourSchool->getStudents()

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

Hava a look at: Metadata Mappings for our Entities看看: 我们实体的元数据映射

Especially @OneToMany in the User class.尤其是用户@OneToMany中的 @OneToMany。 This is basically the same as your school - student relation.这和你的学校-学生关系基本相同。

Also be sure to have a look at: 25.9.也一定要看看: 25.9。 Don't map foreign keys to fields in an entity 不要对实体中的字段进行 map 外键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM