Symfony2 Doctrine抛出NonUniqueResultException

Ajo*_*uve 13 php symfony doctrine-orm

我在请求中抛出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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢你的帮助

Ale*_* B. 33

你可以检查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;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

解决问题您可以设置LIMIT查询并仅获取一个结果->setMaxResults(1).

  • 在提供多个结果的查询中,不要使用`getSingleResult`.要么使用` - > setMaxResults(1)`来限制查询,要么使用`getResult()`来返回结果数组. (5认同)

Alt*_*PHP 7

getSingleResult如果您期望超过1个结果,请不要使用...使用此功能执行结果的单一性检查,这是此功能的意图.

许多选择:

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