虽然预计至少有一行,但未找到查询结果

时间:2015-03-24 08:09:13

标签: php symfony doctrine-orm doctrine

我有以下代码:

/**
     * Search similar category given a string
     * 
     * @param $searchTerm search similar category
     */
    public function findOneSimilarCategory($searchTerm)
    {
        $query = $this->createQueryBuilder('secondLevelCategory')
                ->select('secondLevelCategory')
                ->where('secondLevelCategory.categoryTitle LIKE :searchTerm')
                ->setParameter('searchTerm', $searchTerm)
                ->getQuery();

        $query->useResultCache(true, self::CACHE_RESULT_LIFETIME, md5(__METHOD__ . serialize('category-search-' . $query->getParameters())));
        $query->useQueryCache(true);
        return $query->getSingleResult();
    }

然而这给了我一个错误:

PHP message: PHP Fatal error: Uncaught exception 'Doctrine\ORM\NoResultException' with message 'No result was found for query although at least one row was expected.' in /var/www/Shopious/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php:649

1 个答案:

答案 0 :(得分:51)

您收到此错误是因为您使用的是getSingleResult()方法。如果它甚至找不到单个结果,它会生成异常。如果查询中没有任何结果,您可以使用getOneOrNullResult()来获取NULL。

查询#getSingleResult() :检索单个对象。如果结果包含多个对象,则抛出NonUniqueResultException。如果结果不包含任何对象,则抛出NoResultException。纯/混合区别不适用。