我需要将文档的数组(Doctrine ODM(存储到存储在关系数据库(Doctrine orm(中的实体中。我选择将文档的标识符存储为包含文档标识符逗号分离列表的字符串。
我发现我可以在ORM一侧添加一个后载事件,以延迟加载我的文档:http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/1.2.x/cookbook/混合 - 和mongodb-odm.html
但是documentManager :: getReference方法只允许加载一个对象。难道不是构建类似的东西类似于获取对象列表的方法吗?
我会通过创建一个扩展DoctrineCommonCollectionsAbstractLazyCollection
;
示例代码(未测试(:
<?php
use DoctrineCommonCollectionsAbstractLazyCollection;
use DoctrineODMMongoDBDocumentManager;
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 DoctrineODMMongoDBDocumentManager;
use DoctrineORMEventLifecycleEventArgs;
class MyEventSubscriber
{
public function __construct(DocumentManager $dm)
{
$this->dm = $dm;
}
public function postLoad(LifecycleEventArgs $eventArgs)
{
$order = $eventArgs->getEntity();
$em = $eventArgs->getEntityManager();
$productReflProp = $em->getClassMetadata(EntitiesOrder::class)
->reflClass->getProperty('products');
$productReflProp->setAccessible(true);
$productReflProp->setValue(
$order, new LazyArrayRelationshipCollection($this->dm, DocumentsProduct::class, $order->getProductIds())
);
}
}
,或者您可以采用更"肮脏"的方式并循环循环您的ID,在每个ID上致电DocumentManager::getReference
,然后返回其中的ArrayCollection
,它可能会效法。