2

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

class Node
{
    /** [...]
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /** [...]
     * @ORM\Column(name="name", type="string", length=100, nullable=false)
     */
    private $name;

    /** [...]
     * @ORM\ManyToOne(targetEntity="Node", inversedBy="children")
     */
    private $parent;

    /** [...]
     * @ORM\OneToMany(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);
    }

    // ...

加载这个夹具得到很好的管理:

AppBundle\Entity\Node:
    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();

树干

但是孩子们似乎并没有被填充:

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

0

我错过了什么吗?我怎样才能找回我的孩子?

4

1 回答 1

0

由于夹具没有持久化,Alice 只能依赖 setter/adders 是如何实现的。

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

AppBundle\Entity\Node:
    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);
}

如果在夹具中定义了父级:

AppBundle\Entity\Node:
    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;
}

我想我们甚至可以通过避免递归来管理这两种情况

于 2018-02-22T14:49:30.270 回答