我有学校和学生实体课程。 Students 实体包含一个 schoolId 属性,指示学生所属的学校。
在学校存储库类中,我想创建一个函数,该函数将返回属于该学校的学生对象的集合,因此我希望能够像这样调用该函数:
$oSchool->getStudents();
但是我不确定存储库中是否有该函数是最好的地方,因为到目前为止,我遇到的所有示例都从存储库中调用该函数,如下所示:
$aStudents = $em->getRepository('\Entities\Schools')->getStudents();
这似乎并不引用当前的 school 对象。我假设我必须在函数中引用当前的学校对象,我不知道如何做到这一点。目前,这就是我在学校存储库中的功能:
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;
}
真诚感谢任何帮助。
I have Schools and Students entity classes. Students entity contains a property schoolId that indicates the school a student belongs to.
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:
$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:
$aStudents = $em->getRepository('\Entities\Schools')->getStudents();
This doesn't seem to refer to the current schools 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. Currently this is what my function in the Schools repository looks like:
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.
发布评论
评论(2)
看一下:实体的元数据映射
特别是 User 类中的
@OneToMany
。这和你们的校生关系基本是一样的。另请务必查看:25.9。不要将外键映射到实体中的字段
Hava a look at: Metadata Mappings for our Entities
Especially
@OneToMany
in the User class. This is basically the same as your school - student relation.Also be sure to have a look at: 25.9. Don’t map foreign keys to fields in an entity
只需将
$students
属性添加到您的学校实体(使关联是双向的)。然后你可以调用$yourSchool->getStudents()
请参阅:http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html
just add an
$students
attribute to your school-entity (making the association bidirectional). Then you can just call$yourSchool->getStudents()
See: http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html