从父级删除子集合

Vic*_*Vic 6 php doctrine doctrine-orm

我要疯了.

这是父母:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是孩子:

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

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

对我来说不起作用的是删除这个父母的所有现有孩子.从我的控制器,我做:

$parent = $em->getRepository('Core\Parent')->find(1);
$parent->removeAllChildren();
Run Code Online (Sandbox Code Playgroud)

此时,我可以打电话getChildren(),它是空的.在我的脚本退出之前,我也做了:$em->flush();

但是,我检查数据库表,数据仍然存在!我没理解,这让我疯了.如何删除此父级的所有现有子级?

Phi*_*hil 9

您需要使用Orphan Removal选项,例如

/**
 * @OneToMany(
 *   targetEntity="Core\Parent\Child",
 *   mappedBy="parent",
 *   orphanRemoval=true,
 *   cascade={"persist", "remove"}
 * )
 */
protected $children;
Run Code Online (Sandbox Code Playgroud)