简体   繁体   English

使用DQL优化教义查询

[英]Optimizing doctrine query using DQL

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. 实体用户与其他实体有很多关系,这就是优化查询数量以避免Doctrine的延迟加载的原因。 Then I make this query with DQL using QueryBuilder: 然后,我使用QueryBuilder使用DQL进行此查询:

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 谢谢

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 . 您可以在此页面上找到有关不同类型的JOIN的更多详细信息。

Instead of the innerJoin method you will need to use the leftJoin method. 代替innerJoin方法,您将需要使用leftJoin方法。

(Also, you have a bigger problem: you have way too many JOINs, I'd advise you to review the organization of your entities.) (另外,您还有一个更大的问题:您有太多的JOIN,建议您检查实体的组织。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM