Reputation: 31
Assume that i have an association mapping in Doctrine2.
How to define that i need to fetch all associated objects while querying the main one?
Practically, if i define (Main 1-* Sub) and then access all items in Sub collection, Doctine will execute a single DB request to get every one Sub object. I need to Sub objects be retrieved in a main query (JOIN).
Comments or (preferably) Doctrine RTMs welcome )
Upvotes: 2
Views: 687
Reputation: 56
UserRepository
public function getUsersFromCity($city): Collection
{
return $this->createQueryBuilder('u')
->leftJoin('u.address', 'a')
->addSelect('a')
->andWhere('a.city = :city')
->setParameter('city', $city)
->getQuery()
->getResult()
;
}
Upvotes: 0
Reputation: 26921
If you need that on constant basis (i.e. always fetch all association), declare your associations eager. Consult with Doctrine manual chapters 17-19 for details.
If you need it in just several pieces of code - use DQL
for quering them (manual). This way you'll have to specify all your associations.
$query = $em->createQuery("SELECT u, a FROM User u JOIN u.address a WHERE a.city = 'Berlin'");
$users = $query->getResult();
If you are going to use that query often, it isa good idea to encapsulate it in the Entity class (simple, but not best solution), or create a Repository
for an entity (a bit more involved, but it's "the right way").
Upvotes: 3