2

I have a document which contains references to some other documents. Like most people, I am using a MongoId in an "id" field in URLs in order to view these documents. The situation is that I want to display links to these referenced documents from the main document. In order to get the ID of the referenced document I am using code like this:

$mainDocument->getReferencedDoc()->getId();

The obvious annoyance here is that doctrine will run another query to fetch that referenced document just so I can get the ID. But the ID technically already exists in the main document in the reference field. Shouldn't there be a more efficient way to get only the ID without having to query and hydrate the entire referenced document? Do I have to write custom queries every time I want to do this?

The problem becomes significant when you're generating a large list of the main documents containing links to their referenced documents.

j0k
  • 22,600
  • 28
  • 79
  • 90
MDrollette
  • 6,887
  • 1
  • 36
  • 49
  • I've found mentions of this in the code here: https://github.com/doctrine/mongodb-odm/blob/master/lib/Doctrine/ODM/MongoDB/Proxy/ProxyFactory.php#L267 Now to figure out why it's not working for me. – MDrollette Jul 06 '12 at 19:03

3 Answers3

0

The easiest way to do this, is to add a second property to your Document class.

/**
 * @ReferenceOne(targetDocument="SomeOtherDocument", simple=true)
 */
protected $referencedDoc;

/**
 * @Field(name="referencedDoc", type="string")
 */
protected $referencedDocId;

Now you can just do $document->getReferencedDocId();. I'm not totally sure this is possible because of the type=string. I do use this with the ORM, but haven't used it with ODM yet.

0

It seems it does behave this way since this commit on Feb 6th. So this issue is resolved by using the latest mongodb-odm.

MDrollette
  • 6,887
  • 1
  • 36
  • 49
0

If somebody needs the right way how to get an identifier of a referenced MongoDB document without(!) lazy loading it, that's it:

/** @var $metaData \Doctrine\ODM\MongoDB\Mapping\ClassMetadata */
$metaData = $this->documentManager->getClassMetadata('SomeReferencedDocument');
$metaData->getIdentifierValue($object->getSomeReferencedDocument())

Instead of (which still lazy loads the referenced document, using the newest DoctrineODMBundle):

$object->getSomeReferencedDocument()->getId();