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). 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`))'
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?
Use the Database level onDelete option with Doctrine
@ORM\JoinColumn(name="dealer_id", referencedColumnName="id", onDelete="SET NULL")
explanation from here:
SET NULL sets the column value to NULL when a parent row goes away.
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) :
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