orourkedd
orourkedd

Reputation: 6421

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?

Upvotes: 11

Views: 11771

Answers (3)

blackbishop
blackbishop

Reputation: 32660

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)

Upvotes: 4

Cyril F
Cyril F

Reputation: 1882

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

Upvotes: 9

CappY
CappY

Reputation: 1580

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

Upvotes: 1

Related Questions