【问题标题】:Symfony2 Doctrine throw NonUniqueResultExceptionSymfony2 教义抛出 NonUniqueResultException
【发布时间】:2013-07-22 22:04:44
【问题描述】:

我在请求中抛出 NonUniqueResultException 时遇到问题

public function getLastViewUpdate($view)
{
    $qb = $this->getEntityManager()->createQueryBuilder();

    $result = $qb->select('vu')
        ->from('EasyApp\ApplicationBundle\Entity\ViewUpdate', 'vu')
        ->where('vu.view = :view')
        ->orderBy('vu.date','DESC')
        ->setParameter('view', $view)
        ->getQuery()
        ->getSingleResult();

    return $result;
}

但我不知道为什么,我可能要导入一些东西,但我找不到

CRITICAL - Uncaught PHP Exception Doctrine\ORM\NonUniqueResultException: "" at /Users/antoine/Documents/projects/easyApp/application/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php line 621 

感谢您的帮助

【问题讨论】:

    标签: php symfony doctrine-orm


    【解决方案1】:

    你可以查看getSingleResult函数的声明

    /**
     * Gets the single result of the query.
     *
     * Enforces the presence as well as the uniqueness of the result.
     *
     * If the result is not unique, a NonUniqueResultException is thrown.
     * If there is no result, a NoResultException is thrown.
     *
     * @param integer $hydrationMode
     * @return mixed
     * @throws NonUniqueResultException If the query result is not unique.
     * @throws NoResultException If the query returned no result.
     */
    public function getSingleResult($hydrationMode = null)
    {
        ...
        if (count($result) > 1) {
            throw new NonUniqueResultException;
        }
        ...
    }
    

    解决问题可以设置LIMIT查询,->setMaxResults(1)只能得到一个结果。

    【讨论】:

    • 谢谢它有效,但这不是很合适,我不明白为什么抛出错误会产生严重错误
    • 不是错误,是异常。检查getSingleResult代码,我更新了我的答案。
    • 好的,但是我的页面没有被抓取,并且我在 symfony 中有一个 500 错误
    • 我只有这个“500 Internal Server Error - NonUniqueResultException”
    • 不要在提供多个结果的查询上使用getSingleResult。要么使用->setMaxResults(1) 限制查询,要么使用返回结果数组的getResult()。
    【解决方案2】:

    如果您期望超过 1 个结果,请勿使用 getSingleResult... 使用此函数对您的结果进行唯一性检查,这是此函数的目的。

    很多选择:

    • 使用getSingleResult 并处理异常(如try {...} catch (NonUniuqueResultException $e) {...} 或调整您的数据库结构以避免重复,
    • 使用getSingleResult 并添加setMaxResults(1),但这确实是一种信任数据库模型的奇怪方式,
    • 使用getResult 并对返回的结果执行一些操作。

    【讨论】:

    • 感谢您的回答
    【解决方案3】:

    这只是意味着您有两个或多个 ViewUpdates 具有相同的视图。

    【讨论】:

      猜你喜欢
      • 2014-11-03
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      相关资源
      最近更新 更多