[英]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.