【问题标题】:Symfony OneToMany Assiociations not workingSymfony OneToMany 关联不起作用
【发布时间】:2019-07-19 09:44:29
【问题描述】:

我有 Product 实体和 ProductAttachment 实体。一个产品应该可以有多个附件。我使用了 Doctrine 映射 OneToMnay - ManyToOne 但每次我得到产品时,它都有空的 $files 集合

ProductAttachment 实体

     * @var \Shopsys\ShopBundle\Model\Product\Product
     * 
 @ORM\ManyToOne(targetEntity="Shopsys\ShopBundle\Model\Product\Product", inversedBy="files")
     * @ORM\JoinColumn(nullable=false, name="product_id", referencedColumnName="id")
     */
    public $product;

产品实体

     * @var \Shopsys\ShopBundle\Model\Product\ProductAttachment[]|\Doctrine\Common\Collections\ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="\Shopsys\ShopBundle\Model\Product\ProductAttachment", mappedBy="product", cascade={"persist"})
     */
    public $files;

    public function getFiles()
    {
        return $this->files;
    }

我错过了什么吗?

当我打电话时

dump($product->getFiles());

这就是我得到的

Doctrine\ORM\PersistentCollection #619d
   snapshot private => array ()
   owner private => Shopsys\ShopBundle\Model\Product\Product #e2e7
   association private => array (15)
   em private => Doctrine\ORM\EntityManager #dfae
   backRefFieldName private => "product" (7)
   typeClass private => Doctrine\ORM\Mapping\ClassMetadata #5e75
   isDirty private => false
   collection protected => Doctrine\Common\Collections\ArrayCollection #57e3
   |  elements private => array ()
   initialized protected => false

【问题讨论】:

    标签: php symfony orm doctrine


    【解决方案1】:

    问题是 Doctrine 对集合的延迟加载,这在 PersistentCollection 对象的 initialized 属性上表示 - 在您的情况下是 false。意思是,它没有被初始化。

    这通常非常聪明,因为您通常不需要加载所有实体关系(并且那些相关实体本身可能具有关系等)。相反,持久化集合将充当代理/包装器,并且仅在实际访问集合的某些部分时才加载集合内容。

    一些集合实现有一些有趣的行为,所以我建议不要将集合暴露给实体的“外部”。所以我的建议是将getFiles 更改为return $this->files->toArray() 并使$files 属性private

    不过,这只是一个建议。在任何情况下,您在任何集合上调用 toArray() 都应该对其进行初始化并使其行为与您期望的数组一样。

    【讨论】:

      【解决方案2】:

      我尝试了 Jakumi 的解决方案。它只是对我不起作用。最终对我有用的是(Symfony 4.4)

      public function getItems()
      {
          return iterator_to_array($this->items);
      }
      

      调用该函数也会立即填充对象中的集合。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多