繁体   English   中英

当结果作为数组水合时,如何使用Doctrine 2查询生成器检索外键?

[英]How to retrieve foreign keys using Doctrine 2 Query Builder when the result is hydrated as an array?

$posts = $qb
    ->select('p')
    ->from('MyBundle\Entity\Post', 'p')
    ->getQuery()
    ->getArrayResult();

上面的查询将返回类似(+99列)的信息

id | title | url                    | .... many columns here .....  | created_at
---|--------------------------------|-------------------------------|--------------------
 1 | hello | http://www.google.com/ |  |  - | -  | -  | -  | -  | - | 2017-01-01 00:00:00
 2 | world | http://www.yahoo.com/  |  |  - | -  | -  | -  | -  | - | 2017-01-01 00:00:00

但是,此表有一个FK(user_id),它引用表“ user”。 问题是这样的:查询不会将FK列带入查询结果。 我测试了一下,当结果作为数组水合时(getArrayResult),它将忽略FK的on结果;当结果作为对象水合时(getResult),将FK的结果作为结果。 好的,我阅读了此有用的文章( http://shout.setfive.com/2015/01/31/includes-foreign-keys-in-doctrine2-array-results/ ),并找到了一种将FK作为下面的代码显示(不确定这是否合适,但可以正常工作)

$posts = $qb
    ->select('p')
    ->from('MyBundle\Entity\Post', 'p')
    ->getQuery()
    ->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true)
    ->getArrayResult();

尽管如此,我仍然面临另一个我无法解决的问题。 正如我所说的,此表有+99列。 但是,我不想要所有这些。 我只想要+99中的3个 下面的代码可以正常工作,直到...

$posts = $qb
    ->select(array('p.id', 'p.url'))
    ->from('MyBundle\Entity\Post', 'p')
    ->getQuery()
    ->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true)
    ->getArrayResult();

...直到我在select上添加“ p.user”,它代表FK(指表用户的列ID)。

$posts = $qb
    ->select(array('p.id', 'p.url', 'p.user'))
    ->from('MyBundle\Entity\Post', 'p')
    ->getQuery()
    ->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true)
    ->getArrayResult();

那就是我得到的:

[Doctrine\ORM\Query\QueryException]                                                                                                              
[Semantical Error] line 0, col 10 near 'user FROM MyBundle\Entity\Post': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

尝试类似

->select(array('p.id', 'p.name', IDENTITY(p.user))

这将返回用户的标识符/外键。 我从未使用过select(array())表示法,因此我的示例可能无法立即使用。 但是IDENTITY(entity.association)是您想要的。

这里是:

$posts = $qb
    ->select(array('p.id', 'p.url', 'u.id')) // u.id is your user id, change if your user id is different
    ->from('MyBundle\Entity\Post', 'p')
    ->leftJoin('MyBundle\Entity\User', 'u')
    ->getQuery()
    ->getArrayResult()
;

暂无
暂无

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

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