2012-01-16 67 views
4

我要瘋了。從父母刪除子集合

這是父:

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); 
    } 
} 

這是孩子:

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

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

什麼不工作對我來說是刪除所有現有的孩子這個父。從我的控制,我做的:

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

在這一點上,我可以打電話getChildren(),它是空的。在我的腳本退出之前,我也做一個:$em->flush();

但是,我檢查數據庫表和數據仍然存在!我不明白,這讓我瘋狂。如何刪除該父母的所有現有子女?

回答

8

您需要使用Orphan Removal選項,如

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

OMG,謝謝!就是這個。 – Vic 2012-01-16 04:18:45

+0

但是,'orphanRemoval = true'只有在孩子沒有其他引用時纔會起作用。一旦你添加了一個額外的參考,這將不再工作。 – tobain 2016-08-31 06:46:22

-1

你可以有:

$parent = $em->getRepository('Core\Parent')->find(1); 
foreach($parent->getChildren() as $child) { 
    $em->remove($child); 
} 
$parent->removeAllChildren(); 
$em->flush();