2015-09-27 45 views
1

我有兩個實體:BlogPost和Category。 BlogPost實體與實體類別具有ManyToMany單向關係。我在BlogPost存儲庫中編寫了一個函數,只獲取BlogPost實體的一些字段以及Category實體的所有字段。這是它:如何僅從ManyToMany相關表中的實體中選擇一些字段

private function getLitePosts(){ 
    $q = $this->_em->createQuery(
     'select p.id as pid, p.updateDate, p.postTitle, c from ESGISGabonPostBundle:CorporatePost p left join p.categories c' 
    ); 
    return $q->getResult(); 
} 

當它運行時我得到錯誤:

"message": "[Semantical Error] line 0, col -1 near 'select p.id,': Error: Cannot select entity through identification variables without choosing at least one root entity alias." 

我不知道該如何處理它。我例外地得到這樣的東西(以json表示):

[ 
    { 
     "pid": 1, 
     "updateDate": 2015-09-26T00:00:00+0100, 
     "postTitle": "This is a test", 
     "categories": [ 
      { 
       "id": 1, 
       "title": "Uncathegorized" 
      } 
     ] 
    }, 
    { 
     "pid": 1, 
     "updateDate": 2015-09-26T00:00:00+0100, 
     "postTitle": "This is a test 2", 
     "categories": [ 
      { 
       "id": 1, 
       "title": "Uncathegorized" 
      } 
     ] 
    } 
] 

有人可以幫我嗎?

回答

0

我建議使用查詢生成器進行此簡單操作。

$query = $this->createQueryBuilder('p') 
    ->select('p.id as pid, p.updateDate, p.postTitle, c') 
    ->leftJoin('p.categories', 'c') 
    ->getQuery(); 

return $query->getResult(); 

更多的靈感can be found in this answer

1

我終於找到了一個解決方案:

$query = $this->createQueryBuilder('p') 
     ->select('partial p.{id, updateDate, postTitle}') 
     ->leftJoin('p.categories', 'c') 
     ->addSelect('partial c.{id}') 
     ->getQuery(); 

return $query->getArrayResult(); 

它就像我想要的。謝謝托馬斯Votruba的回答。

相關問題