Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). 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?

like image 492
Frederik Wordenskjold Avatar asked May 27 '13 21:05

Frederik Wordenskjold


1 Answers

Use the Database level onDelete option with Doctrine

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

explanation from here:

  • 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 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) :

  • app/console doctrine:database:drop
  • app/console doctrine:database:create
  • app/console doctrine:schema:update --force
  • ( optional: app/console doctrine:fixtures:load )
like image 155
Nicolai Fröhlich Avatar answered Oct 04 '22 14:10

Nicolai Fröhlich