如何重新排序嵌套树的节点(DoctrineExtensions)

How to reorder the nodes of a nested tree (DoctrineExtensions)

我创建了一个控制器操作来重新排列嵌套树分支的节点。我以 DoctrineExtensions documentation 为例,但代码实际上是在破坏树。我做错了什么?

我的控制器动作代码如下:

public function orderUpdateAction($id)
{
    $order = $this->request->getPost()['order'];
    $parent = $this->getLocationById($id);
    $repository = $this->getRepository();
    $previous = null;

    foreach ($order as $childId) {
        $child = $this->getLocationById($childId);

        if (!$child) {
            throw new \InvalidArgumentException("Unknown location: $childId");
        }

        if ($previous) {
            $repository->persistAsNextSiblingOf($child, $previous);
        } else {
            $repository->persistAsFirstChildOf($child, $parent);
        }

        $previous = $child;
    }

    $this->entitymanager->flush();

    // …
}

verify() returns 出现以下错误:

array (size=8)
  0 => string 'index [1], duplicate on tree root: 1' (length=36)
  1 => string 'index [2], duplicate on tree root: 1' (length=36)
  2 => string 'index [3], duplicate on tree root: 1' (length=36)
  3 => string 'index [4], missing on tree root: 1' (length=34)
  4 => string 'index [5], missing on tree root: 1' (length=34)
  5 => string 'index [6], missing on tree root: 1' (length=34)
  6 => string 'index [7], missing on tree root: 1' (length=34)
  7 => string 'node [3] has invalid left or right values' (length=41)

您应该 $this->entitymanager->flush(); 移动到 foreach 循环。