Symfony 4如何从OneToMany关系中删除实体

时间:2019-02-26 15:44:45

标签: symfony symfony4

我在删除分配给具有OneToMany关系的另一个实体时遇到问题。

我有一个名为Business的实体,它有一个属性“ units”,它是一个OneToMany关系上的Unit实体的集合(Business可以有多个单位)。

当我尝试从数据库中删除单个单元时,我违反了外键,这将不允许我从业务实体中删除该单元。

这是两个实体的精简版本:

业务

/**
 * @ORM\Entity(repositoryClass="App\Repository\BusinessRepository")
 */
class Business
{
    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="App\Entity\Unit", mappedBy="business")
     */
    private $units;

}

单位

/**
 * @ORM\Entity(repositoryClass="App\Repository\UnitRepository")
 */
class Unit
{
    /**
     * @var Business
     * @ORM\ManyToOne(targetEntity="App\Entity\Business", inversedBy="units")
     * @ORM\JoinColumn(name="business_id", referencedColumnName="id")
     */
    private $business;
}

因此在UnitRepository中,我有一个删除方法:

/**
     * @param Unit $unit
     */
    public function delete(Unit $unit){

        $this->em->remove($unit);
        $this->em->flush();
    }

我得到这个错误:

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

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`businessdirectory`.`unit_day`, CONSTRAINT `FK_F03D80CEF8BD700D` FOREIGN KEY (`unit_id`) REFERENCES `unit` (`id`))

我不知道我是否在这里建立了不正确的关系,但是我应该能够从公司中删除一个单位,并且我应该能够删除与其单位中的整个公司。

1 个答案:

答案 0 :(得分:3)

查看单位实体是否是另一个关系的拥有方。此时,您需要删除所有首先依赖于Unit的实体。您可以自由删除一对多关系的拥有方,但是在删除拥有方之前,您需要清除所有拥有的元素。