使用 HYDRATE_ARRAY 强制 'fetch joined' 关系包含其 ManyToOne 关系的 IDENTITY?

Force 'fetch joined' relations to include IDENTITY of their ManyToOne relations using HYDRATE_ARRAY?

我有一个查询,其中我将许多 table 加入到我原来的 Person 实体。一个 Person 可能有多个 Child 关系 (OneToMany),一个 Child 可能有一个 School 他们去 (ManyToOne)。问题是,我不需要连接到每个 child 的整个 School 实体,只需要它们的 id,它已经存储在 Child.

我正在使用 Paginator 遍历结果,我使用 HYDRATE_ARRAY 来减少 ORM 解析数据到实体 objects 的开销。但是未获取关系的 id 字段不会以这种方式返回,因此学校 id 也不是。

我也可以加入 School 实体,但是由于身份已经存储在 Child 记录中,我不明白为什么我应该通过让数据库加入另一个来进一步降低性能table。将结果作为实体 objects 获取也可以解决问题,但也会以性能为代价。我怎样才能让 id 应用结果,而不必不必要地加入 School 实体或不必将结果混合为 objects?

$query = $em->getRepository(Entity\Person::class)->createQueryBuilder('p');

$query
  ->select([
    'p as person',
    'w.name as workplace_name',
    'c',
  ])
  ->leftJoin('p.children', 'c') //Entity\Child
  ->leftJoin('p.workplace', 'w') //Entity\Company
  //...

;
$paginator = new Paginator($query);
$paginator->getQuery()
  ->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);

您可以使用 Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS 在结果中包含外键列值:

$paginator->getQuery()
->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true)
->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);

其中:

The includeMetaColumns query hint causes meta columns like foreign keys and discriminator columns to be selected and returned as part of the query result.

参考

  • Doctrine\ORM\Query documentation
  • How to get association foreign key IDs in Doctrine 2 without loading the associated object?
  • Getting only ID from entity relations without fetching whole object in Doctrine