How to create a function that queries another table for an Entity object in Doctrine 2
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.
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
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
精彩评论