【问题标题】:Store array of doctrine Document into an Entity将教义文档数组存储到实体中
【发布时间】:2018-09-06 21:43:58
【问题描述】:

我需要将一个文档数组(doctrine ODM)存储到一个存储在关系数据库(Doctrine ORM)中的实体中。 我选择将我的文档的标识符存储为一个字符串,其中包含一个逗号分隔的文档标识符列表。

我发现我可以在 ORM 端添加一个 PostLoad 事件来延迟加载我的文档:http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/1.2.x/cookbook/blending-orm-and-mongodb-odm.html

但 DocumentManager::getReference 方法只允许加载单个对象。难道没有办法构建类似于获取对象列表的东西吗?

【问题讨论】:

    标签: php orm doctrine odm


    【解决方案1】:

    我会通过创建一个扩展 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,这可能会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多