我会通过创建一个扩展 Doctrine\Common\Collections\AbstractLazyCollection 的新集合来做到这一点;
示例代码(未测试):
<?php
use Doctrine\Common\Collections\AbstractLazyCollection;
use Doctrine\ODM\MongoDB\DocumentManager;
class LazyArrayRelationshipCollection extends AbstractLazyCollection
{
private $dm;
private $className;
private $ids;
public function __construct(DocumentManager $dm, $className, array $ids)
{
$this->dm = $dm;
$this->className = $className;
$this->ids = $ids;
}
protected function doInitialize()
{
$class = $this->dm->getClassMetadata($this->className);
$this->collection = $this->dm->getRepository($this->className)
->findBy([$class->identifier[0] => $this->ids]);
}
}
和订阅者:
<?php
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ORM\Event\LifecycleEventArgs;
class MyEventSubscriber
{
public function __construct(DocumentManager $dm)
{
$this->dm = $dm;
}
public function postLoad(LifecycleEventArgs $eventArgs)
{
$order = $eventArgs->getEntity();
$em = $eventArgs->getEntityManager();
$productReflProp = $em->getClassMetadata(Entities\Order::class)
->reflClass->getProperty('products');
$productReflProp->setAccessible(true);
$productReflProp->setValue(
$order, new LazyArrayRelationshipCollection($this->dm, Documents\Product::class, $order->getProductIds())
);
}
}
或者您可以采用更“肮脏”的方式并循环遍历您的 ID,在每个 ID 上调用 DocumentManager::getReference,然后返回其中的 ArrayCollection,这可能会起作用。