symfony2中的正确方法,用于检查表中是否存在特定行

时间:2014-06-23 19:34:01

标签: php symfony doctrine-orm

我正在使用symfony2和doctrine。我只想检查表中是否存在特定行。 如果存在,则无需返回该实体的对象。 例如,如果我使用这样的东西来检查是否有人使用$ clientIp的ip访问视频 我只是想要正确或错误的VideoVisit实例。

$query = $this->getEntityManager()->createQuery(
                'SELECT v FROM MjVideoBundle:VideoVisit v'
                . ' WHERE v.video=:videoId'
                . ' AND v.ip=:clientIp')
                ->setParameters(array(
                    'videoId'=> $videoId,
                    'clientIp' => $clientIp));

        try{
        $result = $query->getSingleResult();
    } catch (\Doctrine\Orm\NoResultException $ex) {
        $result = false;
    }

    if($result == false){
        //do something
     }
     else{
        //do something else
     }

1 个答案:

答案 0 :(得分:0)

这是你正在做的很多工作。尝试使用更简单的Doctrine functions that are already provided to you

$video = $this->getDoctrine()->getRepository('MjVideoBundle:Video')->find($videoId);
$result = $this->getDoctrine()->getRepository('MjVideoBundle:VideoVisit')->findOneBy(
    array('video' => $video, 'clientIp' => $clientIp)
);

if ($result) {
    // do something if found
} else {
    // do something if not found
}

注意你也必须使用视频对象进行搜索,你不只是在where条件下搜索视频ID(除非你没有正确设置你的关联映射。)我假设你的名字Video实体,并假设$videoId始终有效。

相关问题