开发者

Doctrine2 - (how to) fetch associated objects with main

开发者 https://www.devze.com 2023-04-02 05:36 出处:网络
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?

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 )


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").


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()
  ;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消