删除所有父子项通过一对多关系连接的实体

时间:2017-01-08 03:13:25

标签: sql doctrine-orm

in CalcResult entity

    /**
     * @ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\CalcResult",inversedBy="buySellResults",cascade={"persist"})
     * @ORM\JoinColumn(name="calcResult_id", referencedColumnName="id")
     */
    private $calcResult;


in BuySellResult entity 

        /**
     * @ORM\OneToMany(targetEntity="Acme\UserBundle\Entity\BuySellResult",mappedBy="calcResult",cascade={"persist"})
     */
    private $buySellResults;

CalcResult行有一些BuySellResult,这两个条目的关系就像父子一样。

当我删除一行BuySellResult行时,我想删除与一个CalcResult行相关联的所有CalcResult行。

但是,当我尝试删除CalcResult行时,

发生此错误。 我该如何解决?

我添加了cascade={"persist"},但我不确定这是实现目标的正确方法。

[3/4] ForeignKeyConstraintViolationException: An exception occurred while executing 'DELETE FROM CalcResult WHERE id = ?' with params [1004]:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`wisdom`.`buysellresult`, CONSTRAINT `FK_C1A2F7B3CFB4BB7` FOREIGN KEY (`calcResult_id`) REFERENCES `CalcResult` (`id`))   +

1 个答案:

答案 0 :(得分:1)

您需要更改

cascade={"persist"}

cascade={"persist", "remove"}, orphanRemoval=true

此处有更多详情: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#orphan-removal