Is it possible to disable lazy loading for ODM Doctrine?

850 views Asked by At

We are developing API with Silex and Doctrine (ODM) and we have object Story, which have property images.

class Story extends AbstractDocument
{
    /** @MongoDB\Id */
    protected $id;

    /**
     * @MongoDB\ReferenceMany(
     *     targetDocument="MyNamespace\Documents\Image",
     *     storeAs="DBRef"
     * )
     */
    protected $images = [];

    // Other properties and methods
}

We have get method in repository (in AbstractRepository, from which extends all other repositories).

public function get(string $documentId) : array
{
    $document = $this->createQueryBuilder()
        ->field('id')->equals($documentId)
        ->hydrate(false)
        ->getQuery()
        ->toArray();
}

This method returns embedded and referenced objects, but for referenceMany returns only ids without data.

Is it possible to deny lazy loading to get all documents ?

One possible solution, which we found - rewrite method toArray.

1

There are 1 answers

2
malarzm On

As soon as you use ->hydrate(false) you are instructing ODM to get out of your way and return you raw data from MongoDB. You are seeing the referenceMany as an array of ids because that is the raw representation, no lazy loading is involved.

The cleanest way to solve your issue would be implementing StoryRepository which would fire an additional query to get referenced images:

public function get(string $documentId) : array
{
    $document = $this->createQueryBuilder()
        ->field('id')->equals($documentId)
        ->hydrate(false)
        ->getQuery()
        ->toArray();
    $document['images'] = /* ... */;
    return $document;
}