未找到查询结果,尽管至少需要一行

2022-08-30 18:02:56

我有以下代码:

/**
     * 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

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

Query#getSingleResult():检索单个对象。如果结果包含多个对象,则会引发非唯一结果异常。如果结果不包含任何对象,则引发 NoResultException。纯/混合的区别不适用。


答案 2

推荐