Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relation OneToOne cascade="persist, remove" not work

I have a relationship OneToOne bidirectional, configurate how cascade persis, remove, but when i call controller eliminarPersonaFisicaAction, this show the next error:

An exception occurred while executing 'DELETE FROM entidad WHERE id = ?' with params [84]:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`xxx`.`personafisica`, CONSTRAINT `FK_D55D20169B1A19BB` FOREIGN KEY (`id_entidad`) REFERENCES `entidad` (`id`)) 

This is my configure in entities: First entity:

//code
/**
     * @ORM\OneToOne(targetEntity="XXX\EntidadBundle\Entity\PersonaFisica", mappedBy="entidad", cascade={"persist", "remove"})
     * @ORM\JoinColumn(name="persona_fisica_id", referencedColumnName="id")
     **/
    private $personaFisica;
//code

Second entity:

//code
/**
     * @ORM\OneToOne(targetEntity="XXX\EntidadBundle\Entity\Entidad", inversedBy="personaFisica", cascade={"persist", "remove"})
     * @ORM\JoinColumn(name="id_entidad", referencedColumnName="id")
     */
    protected $entidad;
//code

eliminarPersonaFisicaAction:

public function eliminarPersonaFisicaAction($id){
    $em = $this->getDoctrine()->getManager();
    $personaFisica = $em->getRepository("EntidadBundle:Entidad")->find($id);
    if($personaFisica->getPresupuestosEnLosQueEsContacto()->isEmpty() && $personaFisica->getPresupuestos()->isEmpty() && $personaFisica->getDocumentos()->isEmpty() && $personaFisica->getAsignacionesExternas()->isEmpty()){
        $em->remove($personaFisica);
    }
    $em->flush();
    return $this->redirect($this->generateUrl('ver_personas_fisicas'));
}
like image 275
Ivan Javier Barranco Gavilan Avatar asked Nov 18 '15 09:11

Ivan Javier Barranco Gavilan


1 Answers

Please note that cascade={"persist", "remove"} only affect the internal Doctrine2 persistence and removal. It has nothing to do with the database.

In order to tell DB to explicitly add 'onDelete' property to the column you should use onDelete="CASCADE"in JoinColumn config.

//code
/**
     * @ORM\OneToOne(targetEntity="XXX\EntidadBundle\Entity\PersonaFisica", mappedBy="entidad", cascade={"persist", "remove"})
     * @ORM\JoinColumn(name="persona_fisica_id", referencedColumnName="id", onDelete="CASCADE")
     **/
    private $personaFisica;
//code

You don't need to specify JoinColumn on two tables, it is enough that only one table have extra id field. From what I see in your code you should add JoinColumn to Entidad entity. That will make Entidad entity to be deleted when PersonaFisica is deleted.

like image 149
Stepashka Avatar answered Sep 25 '22 03:09

Stepashka