Doctrine ODM : PersistentCollection::toArray returns empty array

925 views Asked by At

Here's a definition of the field for the main document:

/**
 * @var ArrayCollection
 * @MongoDB\ReferenceMany(
 *      targetDocument="Some\Namespace\Document\Reference",
 *      sort={"creationDate": "desc"},
 *      simple=true
 * )
 * @Expose
 * @Groups({"Main"})
 * @Type("ArrayCollection<Some\Namespace\Document\Reference>")
 * @var \Some\Namespace\Document\Reference[]
 */
protected $references;

I tried to get a list of main documents and serialized them via JMS Serializer, but I found, that references is empty array. After some investigation, I discovered, that for getReferences, documents returns instance of PersistentCollection for which:

  • count returns 2 [ok]
  • getMongoData returns array of MongoIds [ok]
  • toArray returns empty array [invalid]

Looks like that's because of initialize method, that clears mongoData.

I achived the proper outcome with following code:

/**
 * @VirtualProperty
 * @SerializedName("reference_ids")
 * @Groups("Main")
 * @return array
 */
public function getReferenceIds()
{
    $out = array();

    foreach ($this->getReferences()->getMongoData() as $val) {
        $out[] = (string)$val;
    }

    return $out;
}

But it's only a shortcut and I don't feel, that's a proper solution.

If anyone has an idea how to retrieve these ids or whole documents using PersistentCollection and why initialize method clears mongoData ?

Thanks.

0

There are 0 answers