I have two entities with a one-to-one unidirectional relationship:
class Foo {
...
/**
* @OneToOne(targetEntity="Bar")
*/
private $bar;
...
}
class Bar {
...
}
When I try to delete a Bar entity I get this error:
Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
How do I keep a unidirectional relationship without loosing the ability to delete Bar entities?
With Doctrine 2, this is what you need to do:
class Foo {
...
/**
* @OneToOne(targetEntity="Bar")
* @JoinColumn(name="bar_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $bar;
...
}
class Bar {
...
}
The onDelete="Cascade" will do what CappY said in his answer (setup your foreign key on delete cascade). This way, when you delete your Bar entity the Foo entity associated will be removed too.
In case your prefer not to remove your Foo entity you can simply replace onDelete="Cascade" with onDelete="SET NULL".
You can use the Orphan Removal. It works with one-to-one
, one-to-many
and many-to-many
associations.
You have just to add the orphanRemoval=true
option like this :
@OneToOne(targetEntity="Bar", orphanRemoval=true)
Setup your Foreign Key ON DELETE cascade (this will delete Foo records too) or SET NULL (this will set column to NULL when u delete Bar)
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With