Doctrine2 - unable to delete oneToMany unidirectional object

I get a violation of external constraints when I try to delete an object containing one-to-many unidirectional 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 relationship to its owner in this case (hence the unidirectional relationship). If I try to delete a Dealer object containing associations with machines, I get the following restriction 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 that Doctrine, using cascade = "remove", would take care of this for me.

If I change the association to bidirectional communication, it works. Why does this not work with unidirectional associations?

+8
php orm doctrine2
source share
1 answer

Use the onDelete database parameter with Doctrine

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

explanation here :

  • CASCADE will propagate changes when the parent element changes. (If you delete a row, rows in restricted tables that reference this row will also be deleted, etc.)
  • SET NULL sets the column value to NULL when the parent row leaves.

  • RESTRICT crashes the DELETE attempt of the parent row.


... update the schema of your database before it reports that it does not work :-)

 app/console doctrine:schema:update --force 

if this does not work due to foreign key errors, go in a complicated 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)
+14
source share

All Articles