正在从父集合中删除子集合


Deleting child collection from 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);
    }
}

这就是孩子:

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

然而,我检查了数据库表,数据仍然存在!我不明白,这让我发疯了。如何删除此父项的所有现有子项?

您需要使用孤立删除选项,例如

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

您可以拥有:

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