Doctrine 2 Unilateral unidirectional relationships remove non-party

I have two objects with a one-way unidirectional relation:

class Foo { ... /** * @OneToOne(targetEntity="Bar") */ private $bar; ... } class Bar { ... } 

When I try to delete the Bar object, I get this error:

Integrity constraint violation: 1451 Unable to delete or update parent row: foreign key constraint does not work

How to keep unidirectional communication without losing the ability to delete Bar objects?

+6
source share
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 { ... } 

onDelete = "Cascade" will do what CappY said in its answer (configure your foreign key when deleting the cascade). That way, when you delete your Bar object, the associated Foo object will also be deleted.

If you prefer not to delete your Foo object, you can simply replace onDelete = "Cascade" with onDelete = "SET NULL".

+5
source

You can use Orphan Removal . He works with one-to-one , one-to-many and many-to-many associations.

You need to add the orphanRemoval=true parameter as follows:

 @OneToOne(targetEntity="Bar", orphanRemoval=true) 

Hope this can help someone.

+2
source

Set your foreign key ON DELETE cascade (this will also delete the Foo entries) or SET NULL (this will set the column to NULL when u remove Bar)

http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

+1
source

Source: https://habr.com/ru/post/902891/


All Articles