1

I'm having a bit of a problem deleting an entity assigned to another with a OneToMany relationship.

I have an entity called Business and it has a property "units" which is a collection of Unit entities on a OneToMany relationship (business can have many units).

When i try to delete a single unit from the database i get a violation of the foreign keys, it won't let me remove the unit from the business entity.

Here is a condensed version of both entities:

BUSINESS

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

}

UNIT

/**
 * @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;
}

So in the UnitRepository i have a delete method:

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

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

And i get this error:

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

I don't know if i have set up the relationship incorrectly or not here, but i should be able to delete a single unit from a business, and i should be able to delete the entire business with it's units.

Glen Elkins
  • 867
  • 9
  • 30
  • Check https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_onetomany for table constraints, or check the database config about what to do when removing foreign keys. – J. Almandos Feb 26 '19 at 15:50

1 Answers1

3

See if a Unit entity is the owning side of another relationship. At that point you would need to delete all the entities that depend on Unit first. You can freely delete the owned side of a One-To-Many relationship but you would need to clear all owned elements before deleting the owning side.

JoeRaid
  • 107
  • 1
  • 10
  • AHHH!! right i see, that makes sense, there is another entity that is reliant on the unit. /** * @ORM\OneToMany(targetEntity="App\Entity\UnitDay", mappedBy="unit", cascade={"persist"}) */ private $days; – Glen Elkins Feb 26 '19 at 15:55
  • You're a genius ! I just added remove to the cascade and it works. Thanks! – Glen Elkins Feb 26 '19 at 15:57