2017-08-08 181 views
0

在学说实体我有这个配置:删除多对多关系Doctrine2

/** 
* @var \Doctrine\Common\Collections\ArrayCollection 
* @ORM\ManyToMany(targetEntity="PriceRate", cascade={"all"}, orphanRemoval=true) 
* @ORM\JoinTable(name="product_rates", 
* joinColumns={@ORM\JoinColumn(name="product_id",referencedColumnName="id")}, 
* inverseJoinColumns={@ORM\JoinColumn(name="rate_id",referencedColumnName="id")}) 
*/ 
protected $rates; 

当我删除它首先尝试删除price_rate表的实体,而不是连接表,所以我得到以下错误:

Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (uniski . product_rates , CONSTRAINT FK_15A90A8FBC999F9F FOREIGN KEY (rate_id) REFERENCES price_rate (id))

为什么它不试图先删除连接的表格行?我试图在连接表列添加onDelete语句,但它不起作用。

这是一个单向关系,因为PriceRate被其他实体使用,因此我使用ManyToMany关系。

它的工作的唯一方法是去除实体之前是清除子实体中的ArrayCollection像这样:

$product->removeAllRate(); //it does this: $this->rates->clear(); 

$em->remove($product); 
$em->flush(); 

谢谢!

+0

这篇文章帮助我:https://stackoverflow.com/questions/14257004/doctrine2-symfony2-cascading-remove-integrity-constraint-violation-1451。问候 – Albeis

回答

0

在实体中,您还必须指定ManyToMany关系。这是原因。例如:

/** 
* @ORM\ManyToMany(targetEntity="Product", mappedBy="rates") 
*/ 
private $products; 
+0

可能这就是为什么没有更短的方式来做到这一点,我必须先删除所有的儿童实体。我无法添加另一方的关系,因为费率是由其他类型的实体共享的。如果费率仅用于产品,我可以使用您的解决方案。从archeticture问题的一部分,如果我不改变它,首先删除子实体是olny方式,目前并不坏。 –