3

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);
}
Matteo
  • 37,680
  • 11
  • 100
  • 115
darkbluesun
  • 817
  • 8
  • 15
  • 2
    just alter your constraint at your database level for on delete set null, you don't need to do the work of database with your application code or here is another way using annotations [*Doctrine 2 OneToMany Cascade SET NULL*](http://stackoverflow.com/questions/8858645/doctrine-2-onetomany-cascade-set-null) – M Khalid Junaid Feb 04 '15 at 05:41
  • possibly a duplicate to this: http://stackoverflow.com/questions/12471715/how-exactly-to-use-ondelete-set-null-doctrine2 – Ashish Awasthi Feb 04 '15 at 07:13

1 Answers1

3

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

darkbluesun
  • 817
  • 8
  • 15
Matteo
  • 37,680
  • 11
  • 100
  • 115
  • An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails – Ste Sep 14 '22 at 15:03