Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Doctrine throw NonUniqueResultException

I have a problem throwing NonUniqueResultException in my request

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;
}

But I don't know realy why, I have maybe to import something, but I can't find

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

Thanks for your help

like image 1000
Ajouve Avatar asked Jul 22 '13 22:07

Ajouve


3 Answers

You can check declaration of getSingleResult function

/**
 * 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;
    }
    ...
}

To solve the problem You can set LIMIT to query and get only one result with ->setMaxResults(1).

like image 180
Alexey B. Avatar answered Oct 14 '22 03:10

Alexey B.


Don't use getSingleResult if you expect more than 1 result... Using this function performs a unicity check of your result, it's the intention of this function.

Many choices :

  • Use getSingleResult and deal with exception (like a try {...} catch (NonUniuqueResultException $e) {...} or adjust your DB structure to avoid duplicates,
  • Use getSingleResult and add setMaxResults(1), but this is really a strange way to trust your DB model,
  • Use getResult and do something with returned results.
like image 23
AlterPHP Avatar answered Oct 14 '22 05:10

AlterPHP


It just means that you have two or more ViewUpdates with the same view.

like image 1
Cerad Avatar answered Oct 14 '22 04:10

Cerad