简体   繁体   English

Doctrine2 -(如何)使用 main 获取关联对象

[英]Doctrine2 - (how to) fetch associated objects with main

Assume that i have an association mapping in Doctrine2.假设我在 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.实际上,如果我定义 (Main 1-* Sub) 然后访问 Sub 集合中的所有项目,Doctine 将执行单个 DB 请求以获取每个 Sub 对象。 I need to Sub objects be retrieved in a main query (JOIN).我需要在主查询 (JOIN) 中检索子对象。

Comments or (preferably) Doctrine RTMs welcome )欢迎评论或(最好)Doctrine RTMs)

If you need that on constant basis (ie always fetch all association), declare your associations eager .如果您需要不断地(即始终获取所有关联),请声明您的关联eager Consult with Doctrine manual chapters 17-19 for details.有关详细信息,请参阅教义手册第 17-19 章。

If you need it in just several pieces of code - use DQL for quering them ( manual ).如果您只需要几段代码 - 使用DQL查询它们( 手册)。 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").如果您要经常使用该查询,最好将其封装在 Entity 类中(简单但不是最佳解决方案),或者为实体创建一个Repository (有点复杂,但这是“正确的方法”) )。

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

}

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

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