Symfony2加入查询

时间:2014-09-22 16:24:11

标签: symfony doctrine-orm query-builder

我有一个视频表,在该表中我有字段注释,其中包含其他表中的注释ID,现在我使用连接查询在一个查询中获取,但我如何得到该注释?

这是我的代码:

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

如何从加入的实体获得实际评论?

2 个答案:

答案 0 :(得分: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 :(得分: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();
    }
}

如你所说,你有一个表'视频',在该表中有一个字段'comment',其中包含评论的ID。我想你从“视频”到“评论”都有'oneToMany'关系。通过这个简单的查询,您应该能够获得给定VideoID的所有注释。我没有对此进行测试,但我认为它应该可行。尝试一下并根据需要进行调整。

相关问题