How to hydrate related object in Doctrine MongoDB?

234 Views Asked by At

I'm having trouble hydrating the referencing object in my collection.

I have a Country collection, which looks like this:

Country collection

And then I have a District collection, which has pretty much the same fields as Country, but also has a #[MongoDB\ReferenceOne(storeAs: ClassMetadata::REFERENCE_STORE_AS_ID, targetDocument: Country::class)] reference on parent (Country)

The District collection looks like this:

District collection

So I'm fine with inserting into the collection, but I'm having trouble with fetching it. I want the result to be serialized into Class objects, including the relations. So what I have is Doctrine AggregationBuilder which looks like this:

$this->dm->createAggregationBuilder(District::class)
            ->hydrate(District::class)
            ->lookup('parent')
            ->alias('parent')
            ->getAggregation()
            ->getIterator()
            ->toArray();

This returns hydrated District object

hydrated District object

but there is not information about Country whatsoever. If I would remove the ->hydrate() function, I would finally get the whole result including Country object data. But it would be all in arrays. I also tried adding the

   ->localField('parent')
   ->foreignField('_id')

functions, but that doesn't help either.

Can you help me with how to fetch all the data and serialize/hydrate them into the objects? I'm really trying to get into Mongo, but I'm kind of stuck with this. Thanks

0

There are 0 best solutions below