Question

I use in my code a simple query that works fine in all the cases. This means that if the user has not a photo (for example) the query goes fine:

$user=$em->getRepository('UserBundle:User')->findOneById($id_user);

The entity User has a lot of relations with other entities, this is the reason to optimize the number of queries to avoid Doctrine's lazy loading. Then I make this query with DQL using QueryBuilder:

public function findUsuario($id_user){
    $em = $this->getEntityManager();
    $qb = $em->createQueryBuilder();
    $qb->select('u, p, co, ci, f, s, q, b, r, se, com, t, beb, prof, v, h, i, idi, usf')
       ->from('UserBundle:User', 'u')
       ->innerJoin("u.pais", 'p')
       ->innerJoin("u.comunidad", 'co')
       ->innerJoin("u.ciudad", 'ci')
       ->innerJoin("u.fotos", 'f')
       ->innerJoin("u.sexo", 's')
       ->innerJoin("u.quiero", 'q')
       ->innerJoin("u.busco", 'b')
       ->innerJoin("u.relacionPareja", 'r')
       ->innerJoin("u.sexualidad", 'se')
       ->innerJoin("u.complexion", 'com')
       ->innerJoin("u.tabaco", 't')
       ->innerJoin("u.bebida", 'beb')
       ->innerJoin("u.profesion", 'prof')
       ->innerJoin("u.vivienda", 'v')
       ->innerJoin("u.hijo", 'h')
       ->innerJoin("u.ingreso", 'i')
       ->innerJoin("u.idiomas", 'idi')
       ->innerJoin("u.usuarioFavoritos", 'usf')
       ->where('u.id = :id')
       ->setParameter('id', $id_user);

    $query= $qb->getQuery();
    return $query->getSingleResult();
}

This works well when the user has information on all related entities, but if for example a user has no photo, the following exception occurs: "No result was found for query although at least one row was expected"

I don't understand why, can anyone shed some light? Thanks

Was it helpful?

Solution

An inner join should be used when you want all your rows to have data on the other side of the relationship, if no data exists on the other side of the relationship then the row will be omitted.

You can find more details about the different type of JOINs on this page.

Instead of the innerJoin method you will need to use the leftJoin method.

(Also, you have a bigger problem: you have way too many JOINs, I'd advise you to review the organization of your entities.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top