我试图用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
我错过了什么吗?我怎样才能找到我的孩子?
答案 0 :(得分: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;
}
我想我们甚至可以通过避免递归
来管理这两种情况