gpt4 book ai didi

symfony - 关系一对一级联 ="persist, remove"不起作用

转载 作者:行者123 更新时间:2023-12-04 23:42:24 26 4
gpt4 key购买 nike

我有一个 OneToOne 双向关系,配置如何级联持久化,删除,但是当我调用 Controller eliminarPersonaFisicaAction 时,这显示下一个错误:

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`))

这是我在实体中的配置:
第一个实体:
//code
/**
* @ORM\OneToOne(targetEntity="XXX\EntidadBundle\Entity\PersonaFisica", mappedBy="entidad", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="persona_fisica_id", referencedColumnName="id")
**/
private $personaFisica;
//code

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

消除PersonaFisicaAction:
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'));
}

最佳答案

请注意 cascade={"persist", "remove"}只影响Doctrine2内部的持久化和去除。它与数据库无关。

为了告诉 DB 向列显式添加 'onDelete' 属性,您应该使用 onDelete="CASCADE"JoinColumn配置。

//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

您不需要指定 JoinColumn在两张表上,只有一张表有额外的 id 字段就足够了。根据我在您的代码中看到的内容,您应该添加 JoinColumn到Entidad 实体。这将使 Entidad 实体在 PersonaFisica 被删除时被删除。

关于symfony - 关系一对一级联 ="persist, remove"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33776510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com