Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 One-To-One unidirectional relationship delete non-owning side

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?

like image 314
orourkedd Avatar asked Dec 02 '11 00:12

orourkedd


3 Answers

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".

like image 162
Cyril F Avatar answered Nov 16 '22 12:11

Cyril F


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)
like image 38
blackbishop Avatar answered Nov 16 '22 10:11

blackbishop


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

like image 1
CappY Avatar answered Nov 16 '22 11:11

CappY