2014-09-22 54 views
1

我有一個視頻表,並在該表中我有字段評論其中包含註釋的id,現在我使用連接查詢來獲取,在一個查詢,但我怎麼得到該評論?Symfony2加入查詢

這裏是我的代碼:

$Actions = $this->EntityManager()->getRepository('AppBundle:Video') 
            ->createQueryBuilder('V') 
            ->join('AppBundle:VideoComment', 'VC') 
            ->where('V.videoId = :VideoID') 
            ->andWhere('VC.videoId = :VideoID') 
            ->setParameter('VideoID', $VideoID) 
            ->getQuery() 
            ->getResult(); 

我如何從加盟實體的實際有何評論?

+0

如果你有視頻實體的關係,你可以簡單地瀏覽它(如getComments()) – Matteo 2014-09-22 16:26:50

+0

如果我沒有關係? – SilvioMarijic 2014-09-22 16:43:42

+0

然後你不會明白。再加上你的查詢都搞砸了。 DQL不是SQL。看看文檔中的例子。 – Cerad 2014-09-22 18:21:35

回答

5

你可以做@cezar早些時候說過的,但有一點改變:你必須定義字段以從評論表中檢索相關條目。 所以,您的查詢可能是這樣的:

$em = $this->get('doctrine.orm.entity_manager'); 
$videos = $em->createQuery('select v 
          from YourBundle:Video v 
          left join YourBundle:Comment c 
          where v.comment = c.id') 
      ->getResult(); 

,或者您可以使用查詢生成器做類似的東西:

$videos = $em->createQueryBuilder('v') 
      ->add('select', 'v, c') 
      ->add('from', 'YourBundle:Video v') 
      ->leftJoin('YourBundle:Comment', 'c') 
      ->where('v.comment = c.id') 
      ... // some other conditions if you need 
      ->getQuery() 
      ->getResult(); 

這兩種情況下,我描述賬戶爲視頻和評論實體可能無法在正式的關係(我的意思是他們的關係可能不會在你的教條/ orm文件中描述)。

1

這裏有一個建議:

<?php 
namespace You\AppBundle\Repository; // You is your vendor name, AppBundle is your bundle 

use Doctrine\ORM\EntityRepository; 

class VideoCommentRepository extends EntityRepository 
{ 
    public function getVideoComment($VideoId) 
    { 
     $query = $this->getEntityManager()->createQuery(
      'SELECT v FROM YouAppBundle:Video v LEFT JOIN v.comment c 
      WHERE v.id = :id' 
     )->setParameter('id', $VideoId); 

     return $query->getResult(); 
    } 
} 

正如你說你有一個表,「視頻」,並在該表中有一個字段「註釋」包含註釋的ID。我想你有從'視頻'到'評論'的'一對多'關係。通過這個簡單的查詢,您應該能夠獲得給定VideoID的所有評論。我沒有測試這個,但我認爲它應該工作。嘗試一下,並根據需要進行調整。