简体   繁体   English

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;
}

The Car object should not contain a relation to its owner in this case (hence the unidirectional relationship). 在这种情况下, Car对象不应包含与其所有者的关系(因此是单向关系)。 If I try to delete a Dealer object containing associations to cars, I get the following constraint violation: 如果我尝试删除包含汽车关联的Dealer对象,我会收到以下约束违规:

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`))'

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. 如果我试图从数据库表中手动删除经销商行,我会得到相同的消息,但我认为Doctrine,使用cascade =“remove”,将为我处理这个问题。

If I change the association to a bidirectional association it works. 如果我将关联更改为双向关联,则可以正常工作。 Why does this not work with unidirectional associations? 为什么这不适用于单向关联?

Use the Database level onDelete option with Doctrine 在Doctrine中使用Database level onDelete选项

@ORM\JoinColumn(name="dealer_id", referencedColumnName="id",  onDelete="SET NULL")

explanation from here : 这里解释:

  • CASCADE will propagate the change when the parent changes. 当父级更改时,CASCADE将传播更改。 (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. 当父行消失时,SET NULL将列值设置为NULL。

  • RESTRICT causes the attempted DELETE of a parent row to fail. RESTRICT导致父行的尝试DELETE失败。


... 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) : 如果因外键错误而无法正常工作(按此顺序):

  • app/console doctrine:database:drop app / console doctrine:database:drop
  • app/console doctrine:database:create app / console doctrine:database:create
  • app/console doctrine:schema:update --force app / console doctrine:schema:update --force
  • ( optional: app/console doctrine:fixtures:load ) (可选:app / console doctrine:fixtures:load)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM