简体   繁体   中英

Doctrine MongoDB load associated documents for performance

I have some User documents which reference many Items.

User:

class User
{

    //...

    /**
     * @ODM\ReferenceMany(targetDocument="Item", mappedBy="user", cascade={"remove"})
     */
    protected $items;

     //...

Item:

class Item
{

    /**
     * @ODM\ReferenceOne(targetDocument="User", inversedBy="items")
     */
    protected $user;

I want to display a list of all users with the number of items. So I have one query:

    $users = $dm->getRepository('Acme:User')->findAll();

And I use the count method on the "items" field

    {% for user in users %}
            // ...
            {{ document.items.count }} items
            // ...
    {% endfor %}

The problem is that Doctrine creates a new request for each user, and this leads to memory limits and timeouts.

Is there a way to tell doctrine to load all the items when it does the findAll request? I'd like this to be done only when needed (not in the entity definition but at the query level).

By default doctrine does some lazy loading, eg it doesn't pull the data until it's requested. If you wish to get around lazy loading you need to a fetch join instead of a regular join.

http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#joins

This requires you to write your own query as "findAll()" will not be your friend.

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