简体   繁体   中英

Doctrine makes many queries for one-to-many relationship

I have a Symfony2 app with Doctrine as ORM. In my app i have two entities with one-to-many relations. The one entity is User and the many entity is Item . Their relation config goes below:

User:

oneToMany:
            items:
                targetEntity: App\Bundle\ItemBundle\Entity\Item
                fetch: EAGER
                mappedBy: user

Item:

manyToOne:
        user:
            targetEntity: App\Bundle\UserBundle\Entity\User
            fetch: EAGER
            inversedBy: items
            joinColumn:
                name: user_id
                referencedColumnName: id

The problem is when i'm trying to get the list of Users and their Items , Doctrine creates separate query for each user to fetch it's items.

The query itself is quite simple:

    $entities = $em->getRepository('AppUserBundle:User')->findBy([], [], 30);

Is it possible to fetch all related items for users in one query automatically using Doctrine?

I'm using SF 2.7.6 and doctrine libs with versions:

doctrine/annotations                 v1.2.7  Docblock Annotations Parser
doctrine/cache                       v1.5.1  Caching library offering an ob...
doctrine/collections                 v1.3.0  Collections Abstraction library
doctrine/common                      v2.5.1  Common Library for Doctrine pr...
doctrine/dbal                        v2.5.2  Database Abstraction Layer
doctrine/doctrine-bundle             1.6.0   Symfony DoctrineBundle
doctrine/doctrine-cache-bundle       1.2.1   Symfony Bundle for Doctrine Cache
doctrine/doctrine-migrations-bundle  1.1.1   Symfony DoctrineMigrationsBundle
doctrine/inflector                   v1.0.1  Common String Manipulations wi...
doctrine/instantiator                1.0.5   A small, lightweight utility t...
doctrine/lexer                       v1.0.1  Base library for a lexer that ...
doctrine/migrations                  v1.1.0  Database Schema migrations usi...
doctrine/orm                         v2.5.1  Object-Relational-Mapper for PHP

You can create a method in the repository that performs the joins to avoid the additional queries. It's possible to replace the findBy method with your own implementation but my preference is to create methods that are more descriptive.

Although the examples in the Symfony documentation use DQL , you can use the QueryBuilder if you prefer.

I don't think setting eager fetch is a great idea anyway tbh.

Something like this should work fine:

$users = $this->getEntityManager()
    ->createQueryBuilder()->select('u, i') // key is to select both entities  
    ->from('YourBundle:User', 'u')
    ->join('u.item', 'i')
    ->getQuery()->getResult();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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