5

I'm trying to retrieve content using two items in the URL. Here is the php/symfony code that should do it:

    $em = $this->getDoctrine()->getEntityManager();

    $repository = $this->getDoctrine()
        ->getRepository('ShoutMainBundle:Content');

    $query = $repository->createQueryBuilder('p')
        ->where('p.slug > :slug')
        ->andWhere('p.subtocontentid > :parent')
        ->setParameters(array(
                    'slug' => $slug,
                    'parent'  => $page
                ))
        ->getQuery();

    $content = $query->getSingleResult();

However, when this code is executed it returns the following error:

No result was found for query although at least one row was expected.

I have done some tests, and the data held in the $slug and $page variables hold the correct information. I have also tested the MySQL query and the query brings up the desired result, which confuses me further.

Have I missed something?

mickburkejnr
  • 3,652
  • 12
  • 76
  • 109

4 Answers4

8

As it was answered here

You are getting this error because you are using the getSingleResult() method. it generates an Exception if it can't find even a single result. you can use the getOneOrNullResult() instead to get a NULL if there isn't any result from the query.

Query#getSingleResult(): Retrieves a single object. If the result contains more than one object, an NonUniqueResultException is thrown. If the result contains no objects, an NoResultException is thrown. The pure/mixed distinction does not apply.

Community
  • 1
  • 1
pyjavo
  • 1,598
  • 2
  • 23
  • 41
4

No result was found for query although at least one row was expected.

Another reason could be:

You did this

$query = $this->getEntityManager()
            ->createQuery('
                SELECT u FROM MyBundle:User u
                WHERE u.email = :email')
            ->setParameter('email', $email);

return $query->getSingleResult();

Instead of this

$query = $this->getEntityManager()
            ->createQuery('
                SELECT u FROM MyBundle:User u
                WHERE u.email = :email')
            ->setParameter('email', $email);

$query->setMaxResults(1);

return $query->getResult();
Jonathan
  • 3,016
  • 9
  • 43
  • 74
3

Don't you want to use "=" instead of ">" ?

futurecat
  • 858
  • 7
  • 14
2

If you've got this message because used

$content = $query->getSingleResult();

you can just replace it with the row below

$content = $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR) ?? 0;
David
  • 5,882
  • 3
  • 33
  • 44
muinh
  • 535
  • 6
  • 14
  • No, actually I meant SingleScalarResult as a partial case of this problem. I wrote this because I got this page as a result in google search – muinh Apr 08 '19 at 08:23