If I have a document Shop
that has many Activities
defined as ReferenceMany
, is there a way I can directly query for the list of Activities
for a Shop
without hydrating a Shop
instance?
For example:
{
"_id": fd390j09afj09dfj,
"activities": [
...
]
}
All I want is to be able to say "get me the array activities
where _id
is fd390j09afj09dfj, and hydrate them as Activity
instances.
Here's the first solution I came up with:
/**
* Gets all activities configured for a shop.
*
* @param string $shopId
* @return \BikeShed\Domain\Activity[]|\Doctrine\Common\Collections\ArrayCollection
*/
public function findByShopId($shopId) {
/** @var \BikeShed\Domain\Repository\Shop $shopRepository */
$shopRepository = $this->dm->getRepository('BikeShed\Domain\Shop');
$shop = $shopRepository->findOneById($shopId);
return $shop->getActivities();
}
It's simply fetching the Shop
and then getting all the Activities
via the defined relation.
Here's a working example of how you would implement jmikola's last suggestion:
/**
* @param string $shopId
* @return ActivityModel[]
*/
public function findByShopId($shopId) {
$partialShopData = $this->dm->getRepository('BikeShed\Domain\Shop')->createQueryBuilder()
->hydrate(false)
->field('activities')
->getQuery()
->getSingleResult()
;
$activityIds = [];
if(!empty($partialShopData['activities']))
foreach($partialShopData['activities'] as $activity)
if(!empty($activity['$id']))
$activityIds[] = $activity['$id'];
return $this->createQueryBuilder()
->field('id')
->in($activityIds)
->getQuery()
->toArray()
;
}