读取Onotomany加载的递归树



我正在尝试与爱丽丝和一些涉及递归双向关系的固定装置进行集成测试。

class Node
{
    /** [...]
     * @ORMColumn(name="id", type="integer", nullable=false)
     * @ORMId
     * @ORMGeneratedValue(strategy="IDENTITY")
     */
    private $id;
    /** [...]
     * @ORMColumn(name="name", type="string", length=100, nullable=false)
     */
    private $name;
    /** [...]
     * @ORMManyToOne(targetEntity="Node", inversedBy="children")
     */
    private $parent;
    /** [...]
     * @ORMOneToMany(targetEntity="Node", mappedBy="parent")
     */
    private $children;
    // ...
    public function addChild(Node $child)
    {
        $this->children[] = $child;
        $child->setParent($this);
        return $this;
    }
    public function removeChild(Node $child)
    {
        $this->children->removeElement($child);
        $child->setParent(null);
    }
    // ...

加载此固定装置的管理良好:

AppBundleEntityNode:
    Node-0:
        name: 'Trunk'
    Node-1:
        name: 'Branch 1'
        parent: '@Node-0'
    Node-2:
        name: 'Branch 2'
        parent: '@Node-0'

我可以看到父母:

$loader = new NativeLoader();
$fixtures = $loader->loadFile('node.yml')->getObjects();
echo $fixtures['Node-1']->getParent()->getName();

给出

trunk

,但孩子们似乎没有人口。

echo count($fixtures['Node-0']->getChildren());

0

我想念什么吗?我如何找到我的孩子回来?

由于固定装置没有持久,爱丽丝只能依靠如何实现设置器/加法器。

如果需要将孩子添加到节点:

AppBundleEntityNode:
    Node-0:
        name: 'Trunk'
        children: ['@Node-1', '@Node-2']
    Node-1:
        name: 'Branch 1'
    Node-2:
        name: 'Branch 2'

这是要走的方式:

public function addChild(Node $child)
{
    $this->children[] = $child;
    $child->setParent($this);
    return $this;
}
public function removeChild(Node $child)
{
    $this->children->removeElement($child);
    $child->setParent(null);
}

如果在固定装置中定义了父:

AppBundleEntityNode:
    Node-0:
        name: 'Trunk'
    Node-1:
        name: 'Branch 1'
        parent: '@Node-0'
    Node-2:
        name: 'Branch 2'
        parent: '@Node-0'

必须像这样实现父式设置器:

public function setParent(Node $parent)
{
    $parent->addChild($this);
    $this->parent = $parent;
    return $this;
}

我想我们甚至可以通过避免递归率

来解决两种情况的技巧来管理这两种情况。

最新更新