0

I have a one to many relation in Symfony and I want to achieve the following:

  • When deleting the parent, set null the childs relation field
  • When removing a child from the parent, delete it from the database

What I have now is this: * When deleting the parent, the childs relation field are set to null. OK * When removing a child from the parent, the child relation field is set to null, but it doesnt go away. KO (I want to delete from the database)

My relations:

Parent:

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Childs", mappedBy="parent", cascade={"persist"})
 */
private $childs;

public function getChilds() {
    return $this->childs;
}

public function addChild($child) {
    if ($this->childs->contains($child)) {
        return;
    }

    $child->setParent($this);

    $this->childs[] = $child;
}

public function removeChild($child) {
    if (!$this->childs->contains($child)) {
        return;
    }

    $child->setParent(null);

    $this->childs->removeElement($child);
}

Childs:

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Parent", inversedBy="childs")
 * @ORM\JoinColumn(onDelete="SET NULL")
 */
private $parent;

public function getParent() {
    return $this->parent;
}

public function setParent($parent) {
    $this->parent = $parent;

    return $this;
}

I have tried some combinations but could not get what I want.

Adrian
  • 75
  • 1
  • 11
  • so you have many childs possibly for each parent? If you delete one child of a parent you want the parent to still be deleted? or only if the parent has no more children? for the last one, there's orphanRemoval. – Jakumi Jul 26 '19 at 06:10
  • Yes, I have many childs for each parent (a collection of childs per parent). When I remove one child from the collection I want the child to be removed (but I only get null in the relation field). When the parent is deleted the childs should be orphan (with the relation field set to null) – Adrian Jul 26 '19 at 09:03

0 Answers0