How to delete an entity that can be in an "OneToMany"-relationship

doctrine, one-to-many, symfony

Solution

Person:

/**
* @ORM\ManyToOne(targetEntity="Address", inversedBy="persons")
* @ORM\JoinColumn(name="address_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $address;

Address:

/**
* @ORM\OneToMany(targetEntity="Person", mappedBy="address", cascade={"all"})
*/
protected $persons;

This setup works perfectly for me. When you delete address, person will get NULL in address_id. Cascade all in Address will also save new persons if you do something like:

$address->setPersons(
    array( $person1, $person2 )
) ;

Where $person would be:

$person1 = new Person() ;
$person1->setName(....) ;

In case this doesn't work, please send the code from controller or unit tests. It should be just the most basic code; if you work with address, you just persist address entity. Same for person entity. You don't need to persist both, doctrine will take care of that.

Problem

I have two entities: a `Person` and an `Address`. - a `Person` can have an `Address` - an `Address` can live self-sufficient from a `Person`. I'have created the relationship like this: Address ``` /** * @ORM\OneToMany(targetEntity="Person", mappedBy="address", cascade={"detach"}) */ protected $persons; ``` Person ``` /** * @ORM\ManyToOne(targetEntity="Address", inversedBy="persons", cascade={"detach"}) * @ORM\JoinColumn(name="address_id", referencedColumnName="id") */ protected $address; ``` When I now try to delete an `Address` that is related to a `Person` it results, of course, in an "Integrity constraint violation". How can I tell doctrine to simply detach the `Address` from the `Person`. If tried using `cascade={"detach"}` on both but nothing happens.

Original source