返回使用createQuery的Doctrine查询的结果数

时间:2011-12-12 21:15:14

标签: doctrine-orm

$q = $this->_em->createQuery("SELECT s FROM app\models\Quest s 
                                    LEFT JOIN s.que c
                                    WHERE s.type = '$sub'
                                    AND c.id = '$id'");

根据上面的查询,如何检索结果数?

2 个答案:

答案 0 :(得分:1)

或者可以看一下Doctrine Paginator类对Query对象做什么来获取计数(虽然这种方法很可能是一种矫枉过正,但它会回答你的问题):

public function count()
{
if ($this->count === null) {
    /* @var $countQuery Query */
    $countQuery = $this->cloneQuery($this->query);

    if ( ! $countQuery->getHint(CountWalker::HINT_DISTINCT)) {
        $countQuery->setHint(CountWalker::HINT_DISTINCT, true);
    }

    if ($this->useOutputWalker($countQuery)) {
        $platform = $countQuery->getEntityManager()->getConnection()->getDatabasePlatform(); // law of demeter win

        $rsm = new ResultSetMapping();
        $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count');

        $countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\CountOutputWalker');
        $countQuery->setResultSetMapping($rsm);
    } else {
        $countQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker'));
    }

    $countQuery->setFirstResult(null)->setMaxResults(null);

    try {
        $data =  $countQuery->getScalarResult();
        $data = array_map('current', $data);
        $this->count = array_sum($data);
    } catch(NoResultException $e) {
        $this->count = 0;
    }
}
return $this->count;
}

答案 1 :(得分:0)

您可以事先执行计数查询:

$count = $em->createQuery('SELECT count(s) FROM app\models\Quest s 
                                    LEFT JOIN s.que c
                                    WHERE s.type=:type
                                    AND c.id=:id)
                 ->setParameter('type', $sub);
                 ->setParameter('id', $id);
                 ->getSingleScalarResult();

或者您可以执行查询并获取结果数组的大小:

$quests = $q->getResult();
$count = count($quests);

如果需要计数,请使用第一种方法,以便在实际检索对象之前做出决定。