Skip to content

Incorrect number of database queries when retrieving a document with class inheritance #2723

Open
@parada85

Description

@parada85

Bug Report

Q A
BC Break no
Version 2.9.2

Summary

Problem class inheritance save in entitymap

How to reproduce

I have a simple class inheritance like this:

#[ODM\DiscriminatorMap([3 => Tag::class, 4 => Category::class])]
class Section {}


class Tag extends Section {}
class Category extends Section {}

Then I do something like this:

/** @var DocumentManager $manager */
$manager = Kernel::stGetObj()->getContainer()->get('doctrine_mongodb')->getManager();
$manager->getRepository(Section::class)->find(68);
$manager->getRepository(Section::class)->find(68);

It seems like two database queries are made, but only one should be executed since it should be cached in the entity map. The issue seems to be that when it looks up the entity map, it does so using the repository class, but then stores it with the actual class (the child class) instead.

18:33:35 DEBUG     [doctrine] MongoDB command: {"find":"section","filter":{"_id":68,"type":{"$in":[3,4]}},"limit":1,"$db":"db","lsid":{"id":{"$binary":"R5St6qBWSAqg\/2jT16lktA==","$type":"04"}}}
18:33:35 DEBUG     [doctrine] MongoDB command: {"find":"section","filter":{"_id":68,"type":{"$in":[3,4]}},"limit":1,"$db":"db","lsid":{"id":{"$binary":"R5St6qBWSAqg\/2jT16lktA==","$type":"04"}}}

However, if I do this:

/** @var DocumentManager $manager */
$manager = Kernel::stGetObj()->getContainer()->get('doctrine_mongodb')->getManager();
$manager->getRepository(Tag::class)->find(68);
$manager->getRepository(Tag::class)->find(68);

It works correctly, and only one query is made.

When fetching the same document twice, only one database query should be executed if the entity is already cached in the entity map, regardless of whether the parent or child class is used.

To resolve the issue, I have overridden the find method of the DocumentRepository and do the following:

$parentClass = $this->getReflectionParentClass(new \ReflectionClass($documentName));        
if ($map = $this->getDocumentManager()->getClassMetadata($parentClass->getName())->discriminatorMap) {
     foreach ($map as $class) {
        if ($ret = $this->getDocumentManager()->getUnitOfWork()->tryGetById($id, $this->getDocumentManager()->getClassMetadata($class))) {
            return $ret;
          }
     }
}

but method tryGetById is marked internal :(

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions