簡體   English   中英

Symfony 一對多關聯不起作用

[英]Symfony OneToMany Assiociations not working

我有 Product 實體和 ProductAttachment 實體。 一個產品應該可以有多個附件。 我使用了 Doctrine 映射 OneToMnay - ManyToOne 但每次我拿到產品時,它都有空的 $files 集合

產品附件實體

     * @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

問題是 Doctrine 對集合的延遲加載,這在PersistentCollection對象的initialized屬性上表示 - 在您的情況下是false的。 意思是,它沒有被初始化。

這通常非常聰明,因為您通常不需要加載所有實體關系(並且這些相關實體本身可以具有關系等)。 相反,持久集合將充當代理/包裝器,並且僅在實際訪問集合的某些部分時才加載集合內容。

一些集合實現有一些有趣的行為,所以我建議不要將集合暴露給實體的“外部”。 所以我的建議是更改getFilesreturn $this->files->toArray()並將$files屬性設為private

然而,這只是一個建議。 在任何情況下,您在任何集合上調用toArray()都應該初始化它並使其行為像您期望的數組一樣。

我嘗試了 Jakumi 的解決方案。 它只是對我不起作用。 最后對我有用的是(Symfony 4.4)

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

調用該函數也會立即填充對象中的集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM