Search code examples
phpsymfonydoctrine-ormrelationshipsorphan

Symfony2: Disconnect Associations on delete


I have two entities - Background and Action. a Background has many Actions.

When I delete a Background I want to keep the Action but null the foreign key. Effectively orphaning the entity in a way that will satisfy constraints. I have read so many articles and questions about cascade={"remove"} and orphanRemoval but all of these seem to result either in deleting the orphaned Action (not at all what I want) or doing nothing - which results in an integrity constaint violation.

SQLSTATE[23000]: Integrity constraint violation: 
1451 Cannot delete or update a parent row: 
a foreign key constraint fails (`Action`, CONSTRAINT
`FK_B7722E25C93D69EA` FOREIGN KEY (`background_id`) 
REFERENCES `Background` (`id`)) 

For now the solution I found was to iterate through the related Actions and null the field and persist. This can't be the best way forward.

foreach ($background->getActions() as $action) {
  $action->setBackground(null);
}

Solution

  • You can achieve this with the doctrine ondelete behaviour that can null the references.

    Here an example of how I implemented this in an old sf2.3 project:

    /**
     * Workaround for circular reference:
     * http://stackoverflow.com/questions/14257004/doctrine2-symfony2-cascading-remove-integrity-constraint-violation-1451
     */
    
    /**
     * @ORM\OneToOne(targetEntity="Acme\DashboardBundle\Entity\AlternativeProposal")
     * @ORM\JoinColumn(name="selected_alternative_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     */
    protected $selectedAlternative;
    

    Hope this helps