簡體   English   中英

從集合中刪除元素

[英]Removing elements from collection

我有一個帶有多個圖像的產品。 當我從表單中的產品中刪除圖像時,會將產品引用設置為NULL。 但是,該圖像仍然無故存在於數據庫中。

我想從數據庫中刪除圖像行。 我怎樣才能做到這一點?

我的產品實體

    ...

    /**
     * @ORM\OneToMany(targetEntity="ApplicationShared\Entity\Image", mappedBy="product", cascade={"all"})
     * )
     */
    protected $images;

    ...

    /**
     * Get images.
     *
     * @return array
     */
    public function getImages()
    {
        return $this->images;
    }

    /**
     * Add a image to the product.
     *
     * @param Images
     *
     * @return void
     */
    public function addImages(Collection $images)
    {
        foreach ($images as $image) {
            $image->setProduct($this);
            $this->images->add($image);
        }
    }

    /**
     * @param Collection $images
     */
    public function removeImages(Collection $images)
    {
        foreach ($images as $image) {
            $image->setProduct(null);
            $this->images->removeElement($image);
        }
    }

圖片實體

...

/**
 * @ORM\ManyToOne(targetEntity="ApplicationShared\Entity\Product", inversedBy="images")
 * @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=true, onDelete="CASCADE")
 */
protected $product;

...

/**
 * Allow null to remove association
 *
 * @param Product $product
 */
public function setProduct(Product $product = null)
{
    $this->product = $product;
}

/**
 * Get product.
 *
 * @return array
 */
public function getProduct()
{
    return $this->product;
}

我認為解決方案是orphanRemoval屬性( http://doctrine-orm.readthedocs.org/en/2.0.x/reference/working-with-associations.html#orphan-removal

“當使用orphanRemoval = true選項時,Doctrine假設實體是私有的,不會被其他實體重用。如果您忽略此假設,即使您將孤立的實體分配給另一個實體,您的實體也會被Doctrine刪除。 “

因此,您的OneToMany方面應該像:

@ORM\\OneToMany(targetEntity="ApplicationShared\\Entity\\Image", mappedBy="product", cascade={"all"}, orphanRemoval=true)

暫無
暫無

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

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