1

When deleting an entity, I often check manually if the entity is not linked to others before allowing removing it:

public function deleteAction(Operation $operation)
{
    if ($operation->getArticles()->isEmpty() && $operation->getMessages()->isEmpty()) {
        $em = $this->getDoctrine()->getManager();
        $em->remove($operation);
        $em->flush();
        $this->addFlash('success', sprintf("Operation deleted", $operation));
    } else {
        $this->addFlash('danger', sprintf("Can't delete operation.", $operation));
    }

    return $this->redirectToRoute('operation');
}

But this method implies knowing all the relations between the entity and others and I have to check for each one. Using try...catch instead is sometimes useful, but the deletion not always raises an exception.
Is there another (more generic) way to check for existence of references to my entity before deleting it?

Roubi
  • 1,989
  • 1
  • 27
  • 36
  • 2
    I am somewhat confused as to what you are trying to do. Can't you use DB-level constraints or even ORM-level? https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/working-with-associations.html#transitive-persistence-cascade-operations – Alex.Barylski Mar 11 '19 at 15:07
  • 1
    I had a loosely related [question](https://stackoverflow.com/questions/54967881/catch-integrity-constraint-violation-19-foreign-key-constraint-failed-when-de). You can throw a look how it was solved. Eventually it might provide you some hints. – cezar Mar 11 '19 at 18:04
  • @Alex.Barylski If my Foo Entity references the entity I want to delete with a non bidirectionnal ManyToMany , I can delete a record without getting `Integrity constraint violation` but I'll get it later on when accessing my Foo entity. That's why I would like to check beforehand – Roubi Mar 11 '19 at 18:22

0 Answers0