Item.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php

namespace Entities;

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="type", type="integer")
 * @DiscriminatorMap({"0" = "Item", "1" = "SubItem"})
 */
class Item
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @OneToMany(targetEntity="Child", mappedBy="parent", cascade={"remove"})
     */
    protected $children;

    public function __construct()
    {
        $this->children = new \Doctrine\Common\Collections\ArrayCollection;
    }

    public function getChildren()
    {
        return $this->children;
    }
}

Child.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php

namespace Entities;

/**
 * @Entity
 */
class Child
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @ManyToOne(targetEntity="Item", inversedBy="children")
     * @JoinColumn(name="parentId", referencedColumnName="id")
     */
    public $parent;
}

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php

// ... 

$item = new Entities\SubItem;
$child = new Entities\Child;
$child->parent = $item;
$item->getChildren()->add($child);
$em->persist($item);
$em->persist($child);
$em->flush();
$em->clear();

$item = $em->find('Entities\Item', $item->id); 

$em->remove($item);
$em->flush(); // Crashes