Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting child collection from parent

I'm going crazy.

This is the parent:

class Parent {
    /**
     * @Id
     * @GeneratedValue
     * @Column(type="integer")
     */
    protected $id;

    /**
     * @OneToMany(targetEntity="Core\Parent\Child", mappedBy="parent", cascade={"persist", "remove"})
     */
    protected $children;


    public function __construct() {
        $this->children = new \Doctrine\Common\Collections\ArrayCollection();
    }


    public function getChildren() {
        return $this->children->toArray();
    }

    public function removeAllChildren() {
        $this->children->clear();
    }

    public function addChild($child) {
        $this->children->add($child);
    }
}

This is the child:

class Child {
    /**
     * @Id
     * @GeneratedValue
     * @Column(type="integer")
     */
    protected $id;

    /**
     * @ManyToOne(targetEntity="Core\Parent", inversedBy="children")
     * @JoinColumn(name="parent_id", referencedColumnName="id")
     */
    protected $parent;
}

What is not working for me is deleting all EXISTING children for this parent. From my controller, I do:

$parent = $em->getRepository('Core\Parent')->find(1);
$parent->removeAllChildren();

At this point, I can call getChildren() and it is empty. Before my script quits, I also do an: $em->flush();

However, I check the database tables and the data is still there! I don't get it, and it's driving me insane. How do I delete all the existing children for this parent?

like image 805
Vic Avatar asked Jan 16 '12 02:01

Vic


1 Answers

You need to use the Orphan Removal option, eg

/**
 * @OneToMany(
 *   targetEntity="Core\Parent\Child",
 *   mappedBy="parent",
 *   orphanRemoval=true,
 *   cascade={"persist", "remove"}
 * )
 */
protected $children;
like image 66
Phil Avatar answered Oct 10 '22 02:10

Phil