2017-02-16 60 views
0
$posts = $qb 
    ->select('p') 
    ->from('MyBundle\Entity\Post', 'p') 
    ->getQuery() 
    ->getArrayResult(); 

上面的查詢將返回這樣的事(+99列)如何使用Doctrine 2查詢生成器時,結果被水合成一個數組檢索外鍵?

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)是指表 「用戶」。問題是這樣的:查詢不會將FK列帶入查詢結果中。我測試和當結果被水合作爲陣列(getArrayResult)它忽略FK對結果,當它帶來FK對結果的結果被水合爲對象(的getResult)。好吧,我看這是很有幫助的職位(http://shout.setfive.com/2015/01/31/including-foreign-keys-in-doctrine2-array-results/),並計算出

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

但是我面對的另一個課題的方式檢索FK如下所示的代碼(不知道這是適當的方式,但在工程)目前我無法解決這個問題。正如我所說的這個表格有+99欄。但是,我不想要所有這些。 我想什麼是隻有3 +99。以下正常工作,直到代碼...

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

...直到我添加上選擇「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. 

回答

1

試着這麼做

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

這將返回的標識符/外鍵的用戶。 我從來沒有與select(array())符號的工作,所以我的例子可能不開箱的工作。但IDENTITY(entity.association)是你在找什麼。

+0

工作得很好!欣賞它! –

0

這就是:

$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() 
; 
+0

uhmm是它的工作原理,但我需要創建一個不必要的加入,因爲FK已經在主表。如果我有10個FK呢?我應該加入10個不同的表格嗎?因爲我已經把它們全部放在我的主表格中了? –

相關問題