mickburkejnr
mickburkejnr

Reputation: 3690

"No result was found for query although at least one row was expected." Query should display records though in Symfony

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?

Upvotes: 6

Views: 13465

Answers (4)

muinh
muinh

Reputation: 605

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;

Upvotes: 3

pyjavo
pyjavo

Reputation: 1613

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.

Upvotes: 8

Jonathan
Jonathan

Reputation: 3024

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();

Upvotes: 4

futurecat
futurecat

Reputation: 858

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

Upvotes: 3

Related Questions