开发者

Doctrine MongoDB ODM load referenced documents

my szenario in detail, iv'e got one Us开发者_StackOverflower Document:

/** @Document(collection="user") */
class User
{
    /** @Id */
    private $id;

    /** @ReferenceMany(targetDocument="Pet") */
    private $pet;

    public function getPet()
    {
        return $this->pet;
    }
}

and iv'e got one Pet document:

/** @Document(collection="pet") */
class Pet
{
    /** @Id */
    private $id;

    /** @ReferenceMany(targetDocument="User") */
    private $user;

    public function getUser()
    {
        return $this->user;
    }
}

A many to many correlation. If i call the following code for an existing document...

$result = $this->_dbContainer->getDocumentManager()->getRepository('User')->findBy(array('id' => => 'XZTZHJ323LKFHGJKLHGFGHJK'));
print_r($result->toArray());

...it ends in an endless loop. Error message:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 112721921 bytes) in ...

If i execute the following code:

var_dump($result->count());

The result ist one / it exist (everything ok). A var_dump of $result->current() is NULL. The method getMongoData returns the following data (which is correct):

Array ( [0] => Array ( [$ref] => example [$id] => MongoId Object ( [$id] => 4ddac7667294c79e17000002 ) [$db] => test ) )

If i execute the following code:

var_dump($result->current());

The result is boolean (false).

Any ideas?


try regenerating hydrator classes.


Provided your model looks something like this

/**
 * @Document
 */
class User
{
    /** @Id */
    private $id;

    /** @ReferenceMany(targetDocument="Something") */
    private $somethings;

    public function __construct()
    {
        $this->somethings = new \Doctrine\Common\Collections\ArrayCollection;
    }

    public function getSomethings()
    {
        return $this->somethings;
    }
}

You should be able to retrieve the referenced models using

$user = $dm->find('User', $id);
$somethings = $user->getSomethings();
$firstSomething = $somethings->current(); // will return false if empty, can also use first()
foreach ($somethings as $something) {
    // and so on
}

Do not attempt to var_dump() or print_r() the model proxy objects. These contain many recursive references and you will exhaust your available memory attempting to render them as output.


Solution to get a single object from a referenced collection:

$pets = $this->user->getPets();     
if(!is_null($pets) && $pets->count() > 0) {
   $this->pet = $pets->first();
}

Biggest learning (thanks to @Phil):

Do not attempt to var_dump() or print_r() the model proxy objects. These contain many recursive references and you will exhaust your available memory attempting to render them as output.

Best regards, Stephan

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜