Doctrine2 - 无法删除具有单向oneToMany关系的实体 [英] Doctrine2 - Cannot delete an entity with a unidirectional oneToMany relation
问题描述
当尝试删除包含单向一对多关联的实体时,我得到外部约束违规。我有以下简单的课程:
I'm getting a foreign constraint violation when trying to delete an entity, containing unidirectional one-to-many associations. I have the following simple class:
class Dealer{
/**
* @ManyToMany(targetEntity="Car", cascade={"persist", "remove"})
* @JoinTable(name="dealer_cars",
* joinColumns={@JoinColumn(name="dealer_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="car_id", referencedColumnName="id",
unique=true)}
* )
**/
protected cars;
}
Car
在这种情况下,不应该包含与其所有者的关系(因此是单向关系)。如果我尝试删除包含与汽车相关联的经销商
对象,我会遇到以下约束违规:
The Car
object should not contain a relation to its owner in this case (hence the unidirectional relationship). If I try to delete a Dealer
object containing associations to cars, I get the following constraint violation:
Cannot delete or update a parent row: a foreign key constraint fails
(`application`.`dealer_cars`, CONSTRAINT `FK_E1BCEEEBC3C6F69F`
FOREIGN KEY (`car_id`) REFERENCES `car` (`id`))'
如果我尝试删除经销商行手动从数据库表,但我认为使用cascade =删除的Doctrine将为我照顾这个。
I would get the same message if I tried to delete the dealer row manually from the database table, but I thought Doctrine, using cascade="remove", would take care of this for me.
如果我将关联更改为双向关联它工作。为什么这不适用于单向关联?
If I change the association to a bidirectional association it works. Why does this not work with unidirectional associations?
推荐答案
使用Doctrine的数据库级别onDelete选项
Use the Database level onDelete option with Doctrine
@ORM\JoinColumn(name="dealer_id", referencedColumnName="id", onDelete="SET NULL")
来自此处的
解释:
explanation from here:
- 当父级更改时,CASCADE会传播更改。 (如果删除一行,引用该行的约束表中的行也将被删除等)。
-
当设置父列行时,SET NULL将列值设置为NULL
- CASCADE will propagate the change when the parent changes. (If you delete a row, rows in constrained tables that reference that row will also be deleted, etc.)
SET NULL sets the column value to NULL when a parent row goes away.
RESTRICT导致父列的尝试DELETE失败。
RESTRICT causes the attempted DELETE of a parent row to fail.
... 更新您的数据库模式之前,抱怨它不工作: - )
... update your database schema prior to complaining it's not working :-)
app/console doctrine:schema:update --force
如果由于外键错误而无法正常工作,那么(以这个顺序):
if this is not working due to foreign key errors go the hard way (in this order) :
- 应用程序/ console doctrine:database:drop
- app / console doctrine:database:create
- app / console doctrine:schema:update --force
-
- (可选:app / console doctrine:fixtures:load)
这篇关于Doctrine2 - 无法删除具有单向oneToMany关系的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!