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

Symfony 4 how to delete entity from OneToMany relationship

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

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

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

这是两个实体的精简版:

商业

/**
 * @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`))

我不知道我在这里设置的关系是否不正确,但我应该能够从企业中删除单个单位,并且我应该能够删除整个企业及其单位。

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