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

风流意气都作罢 提交于 2021-01-29 10:58:19

问题


I have a query in which I'm joining a number of tables to my original Person entity. A Person may have multiple Child relations (OneToMany), and a Child may have a School they go to (ManyToOne). Problem is, I don't need the entire School entity that connects to each child, only their id, which is already stored on Child.

I'm using a Paginator to iterate through the results and I use HYDRATE_ARRAY to reduce overhead of the ORM parsing data to entity objects. But the id fields of unfetched relations are not returned this way, and thus, the School id isn't either.

I may join the School entity too, but since the identity is already stored on the Child records, I don't see why I should further reduce performance by having the database join another table. Fetching results as entity objects would also solve the problem, but also at the cost of performance. How can I get the id to apper the results without having to unnecessarily join the the School entity or having to hydrate the results as 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);

回答1:


You can use Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS to include the foreign key column values in the result:

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

which:

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

Reference

  • 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


来源:https://stackoverflow.com/questions/54170887/force-fetch-joined-relations-to-include-identity-of-their-manytoone-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!