1

我正在尝试从具有 id、游戏(外键)和日期的表 Comment 中检索评论。

每次我要求评论时,我都想获得 3 条按日期排序的指定游戏的评论,并且我想知道以后是否还有更多评论要显示。为此,我编写了两个函数,第一个函数返回三个注释:

public function getRecentComments($offset,$id) {
    $dql = "SELECT c FROM Comment c 
        WHERE c.game = ?1
        ORDER BY c.date DESC";
    $query = $this->getEntityManager()->
        createQuery($dql)->
        setParameter(1, (int)$id)->    
        setMaxResults(3)->
        setFirstResult($offset);
    return $query->getResult();

第二个返回我以后可以得到的评论数量。此功能的原因是是否显示“更多评论”按钮。这是第二个功能:

public function moreComments($offset,$id) {

    $dql = "SELECT COUNT(c.id) FROM Comment c
        WHERE c.game = ?1
        ORDER BY c.date DESC";
    $query = $this->getEntityManager()
        ->createQuery($dql)
        ->setParameter(1, (int)$idPartido)
        ->setFirstResult($offset+3)    
        ->setMaxResults(1)
        ->getSingleScalarResult();

    return $query;
}

但是第二个功能不适用于下一个错误:

致命错误:未捕获的异常 'Doctrine\ORM\NoResultException' 带有消息 'No result was found for query 尽管预期至少有一行。

我认为这是由于使用了 setFirstResult 和 count()。

所以,我用过

public function moreComments($offset,$id) {

    $dql = "SELECT c FROM Comentario c
        WHERE c.partido = ?1
        ORDER BY c.fecha DESC";
    $query = $this->getEntityManager()
        ->createQuery($dql)
        ->setParameter(1, (int)$idPartido)
        ->setFirstResult($offset+3)    
        ->setMaxResults(1)
        ->getSingleScalarResult();

    return sizeof($query);
}

这显然写得不好,因为我不应该只为计数而获取数据。我怎样才能正确编写第二个函数?

提前致谢。

4

1 回答 1

4

如果您只使用 MySQL,那么您可以利用它的FOUND_ROWS()功能。

这将需要使用本机查询,这很可能会妨碍您使用 MySQL 以外的数据库的能力,但根据我的经验,它工作得很好。

我已经成功地使用了以下类似的东西。

use Doctrine\ORM\Query\ResultSetMapping;

public function getRecentComments($offset, $id) {
    $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM Comment c 
        WHERE c.game = ?
        ORDER BY c.date DESC
        LIMIT ?,3";
    $rsm = new ResultSetMapping();
    $rsm->addEntityResult('Comment', 'c');
    $rsm->addFieldResult('c', 'id', 'id');
    $rsm->addFieldResult('c', 'game_id', 'game_id');
    $rsm->addFieldResult('c', 'date', 'date');
    $query = $this->getEntityManager()->createNativeQuery($dql, $rsm);
    $query->setParameters(array(
      (int)$id,
      (int)$offset
    ));
    $results = $query->getResult();

    // Run FOUND_ROWS query and add to results array
    $sql = 'SELECT FOUND_ROWS() AS foundRows';
    $rsm = new ResultSetMapping();
    $rsm->addScalarResult('foundRows', 'foundRows');
    $query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
    $foundRows = $query->getResult();
    $results['foundRows'] = $foundRows[0]['foundRows'];

    return $results;
}

从上述函数获得结果数组后,我将“foundRows”元素提取到一个单独的变量中,取消设置它(即,unset($results['foundRows'])),然后继续正常使用该数组。

希望这可以帮助。

于 2012-07-14T09:09:16.910 回答