我有一个包含多个图像的产品。当我从表单中的产品中删除图像时,它将产品引用设置为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;
}
我认为解决方案是孤儿移除属性(http://doctrine-orm.readthedocs.org/en/2.0.x/reference/working-with-associations.html#orphan-removal)
"当使用orphanRemoval=true选项时,原则假设实体是私有的,不会被其他实体重用。如果你忽略了这个假设,你的实体将被Doctrine删除,即使你将孤立的实体分配给另一个。"
所以你的OneToMany应该是这样的:
@ORM'OneToMany(targetEntity="ApplicationShared'Entity'Image", mappedBy="product", cascade={"all"}, orphanRemoval=true)