I have two types of objects User
and Company
whose data is stored in MongoDB collections user
and company
. User
contains a reference to Company
. I can query for user using the following code in the UserRepository:
$this
->createQueryBuilder()
->field('employer')->references($company);
Company
however is a heavy used object which is cached using Redis. When no cache is present, everything works fine. But when the company instance was fetched from the cache. The Doctrine unit of work does not know about the instance. Executing the code above will therefore result in the following error:
Cannot create a DBRef for class App\Document\Company without an identifier. Have you forgotten to persist/merge the document first?
I have found out that I can use a hack to register the company with the unit of work after fetching it from Redis:
$company = $this->fetchFromCache($params);
$documentManager->getUnitOfWork()->registerManaged($company, $company->getId(), []);
However, this seems ugly. Is there a way that I can query for the users without having to let Doctrine know about the Company object, or changing my datamodel?