2012-01-16 68 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();