简体   繁体   English

从集合中删除元素

[英]Removing elements from collection

I've a product with multiple images. 我有一个带有多个图像的产品。 When I delete an image from the product in my form, it's setting the product reference to NULL. 当我从表单中的产品中删除图像时,会将产品引用设置为NULL。 But, the image still exists in the database for no reason. 但是,该图像仍然无故存在于数据库中。

I want to remove the image row from the database to. 我想从数据库中删除图像行。 How can I do this? 我怎样才能做到这一点?

My product entity 我的产品实体

    ...

    /**
     * @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);
        }
    }

Image entity 图片实体

...

/**
 * @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;
}

I think the solution is the orphanRemoval property ( http://doctrine-orm.readthedocs.org/en/2.0.x/reference/working-with-associations.html#orphan-removal ) 我认为解决方案是orphanRemoval属性( http://doctrine-orm.readthedocs.org/en/2.0.x/reference/working-with-associations.html#orphan-removal

"When using the orphanRemoval=true option Doctrine makes the assumption that the entities are privately owned and will NOT be reused by other entities. If you neglect this assumption your entities will get deleted by Doctrine even if you assigned the orphaned entity to another one." “当使用orphanRemoval = true选项时,Doctrine假设实体是私有的,不会被其他实体重用。如果您忽略此假设,即使您将孤立的实体分配给另一个实体,您的实体也会被Doctrine删除。 “

So your OneToMany side should be like: 因此,您的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