Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a Doctrine MongoDB ODM Document Proxy to convert to the 'original' document?

I have a document Person referenced in document User. When I retrieve User, it doesn't have a Person object embedded, but a Person proxy object. Is there a way to "force" the proxy to become a "full" document (so Person proxy => Person).

I've tried calling a method to retrieve additional data (so __load gets triggered, but the object remains the 'proxy' version.

I hope someone can shed more light on this than the ODM's documention does.

like image 481
Teun Avatar asked Jun 08 '11 14:06

Teun


2 Answers

You can accomplish this by Priming References.

Example Documents:

/** @Document */
class User
{
    /** @ReferenceOne(targetDocument="Person") */
    private $person;
}

/** @Document */
class Person
{
    // ...
}

Using the QueryBuilder:

/* @var $user User */
$user = $dm->createQueryBuilder('User')
    ->field('person')->prime(true)
    ->getQuery()
    ->getSingleResult();
like image 128
leek Avatar answered Oct 15 '22 10:10

leek


You shouldn't need to extract the original object, since the Proxy class should be 100% transparent to your code.

If you need to serialize the document, for example to send it through an API, be sure to correctly implement the serialize() method on your Document.

If you still need to get the referenced document without the proxy, you can either prime() it or fetch it with a separate query specifying the hydrate(false):

$user = $dm->createQueryBuilder('Person')
            ->field('_id')->equals($user->getPerson()->getId())
            ->hydrate(false)

See: Doctrine ODM Doc: Disabling hydration for more info.

like image 45
Madarco Avatar answered Oct 15 '22 10:10

Madarco