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?
You need to use the Orphan Removal option, eg
/**
* @OneToMany(
* targetEntity="Core\Parent\Child",
* mappedBy="parent",
* orphanRemoval=true,
* cascade={"persist", "remove"}
* )
*/
protected $children;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With