ja1cap/doctrine2-nestedset

dev-master 2013-11-11 22:14 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:35:52 UTC


README

这个 Doctrine2 扩展实现了 Doctrine2 的嵌套集合模型(修改后的前序遍历算法)。这允许在关系数据库的平坦表中存储层次化数据,这是一种数据集合,其中每个项都有一个父项和零个或多个子项。有关嵌套集合模型的更多信息,请参阅

https://dev.mysqlserver.cn/tech-resources/articles/hierarchical-data.html

简介

嵌套集合是一个用于存储层次化数据的高效读取访问解决方案。然而,更新嵌套集合树的成本较高。因此,此方案最适合频繁读取而不是频繁写入的层次结构。由于网络的特点,这对于大多数网络应用来说都是适用的。

设置

要将您的模型设置为嵌套集合,您的实体类必须实现 DoctrineExtensions\NestedSet\Node 接口。每个实体类必须包含用于存储嵌套集合左右值的映射字段。

以下是一个使用注解映射的示例

namespace Entity;

use DoctrineExtensions\NestedSet\Node;

/**
 * @Entity
 */
class Category implements Node
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    private $id;

    /**
     * @Column(type="integer")
     */
    private $lft;

    /**
     * @Column(type="integer")
     */
    private $rgt;

    /**
     * @Column(type="string", length="16")
     */
    private $name;


    public function getId() { return $this->id; }

    public function getLeftValue() { return $this->lft; }
    public function setLeftValue($lft) { $this->lft = $lft; }

    public function getRightValue() { return $this->rgt; }
    public function setRightValue($rgt) { $this->rgt = $rgt; }

    public function getName() { return $this->name; }
    public function setName($name) { $this->name = $name; }

    public function __toString() { return $this->name; }
}

通常,您不需要,也不应该与左右字段交互。这些字段内部用于管理树结构。

多棵树

嵌套集合实现可以配置为允许您的表具有多个根节点,因此可以在同一表中存储多棵树。这是通过实现 DoctrineExtensions\NestedSet\MultipleRootNode 接口(而不是 DoctrineExtensions\NestedSet\Node)并映射根字段来实现的。

扩展我们的注解示例

/**
 * @Column(type="integer")
 */
private $root;

public function getRootValue() { return $this->root; }
public function setRootValue($root) { $this->root = $root; }

与左右字段一样,您通常不需要与根值交互。

处理树

在成功设置您的模型为嵌套集合后,您就可以开始使用它了。使用 Doctrine2 的嵌套集合实现主要涉及两个类:Manager 和 NodeWrapper。NodeWrapper 包装您的实体类,让您能够访问底层的树结构。Manager 提供创建新树和获取现有树的方法。

要从数据库中获取整个树

$config = new Config($em, 'Entity\Category');
$nsm = new Manager($config);
$rootNode = $nsm->fetchTree(1);

在这个示例中,$rootNode 是一个包装了您的模型根节点的 NodeWrapper 实例。要获取您的模型对象

$modelObject = $rootNode->getNode();

创建根节点

$config = new Config($em, 'Entity\Category');
$nsm = new Manager($config);

$category = new Category();
$category->setName('Root Category 1');

$rootNode = $nsm->createRoot($category);

插入节点

$child1 = new Category();
$child1->setName('Child Category 1');

$child2 = new Category();
$child2->setName('Child Category 2');

$rootNode->addChild($child1);
$rootNode->addChild($child2);

删除节点

您必须始终使用 NodeWrapper::delete() 方法而不是 EntityManager 的 delete 方法来删除节点。NodeWrapper::delete() 会负责在删除节点时更新树

$category = $em->getRepository('Entity\Category')->findOneByName('Child Category 1');
$node = $nsm->wrapNode($category);
$node->delete();

删除节点也将删除该节点的所有后代。因此,如果您不想删除它们,请确保在删除节点之前将它们移动到其他地方。

移动节点

移动节点很简单。NodeWrapper 提供了多种方法来在树之间移动节点

  • moveAsLastChildOf($other)
  • moveAsFirstChildOf($other)
  • moveAsPrevSiblingOf($other)
  • 检查节点

您可以使用以下一些函数检查节点及其类型

检查和获取兄弟节点

$isLeaf = $node->isLeaf();
$isRoot = $node->isRoot();

您可以使用以下方法检查节点是否有任何兄弟节点

您也可以使用以下方法获取存在的下一个或上一个兄弟节点

$hasNextSib = $node->hasNextSibling();
$hasPrevSib = $node->hasPrevSibling();

如果您想获取所有兄弟节点的数组,可以使用 getSiblings() 方法

$nextSib = $node->getNextSibling();
$prevSib = $node->getPrevSibling();

检查和获取子节点

$siblings = $node->getSiblings();

您可以使用以下方法检查节点是否有父节点或子节点

您可以使用以下方法获取节点的第一个和最后一个子节点

$hasChildren = $node->hasChildren();
$hasParent = $node->hasParent();

或者如果您想获取节点的父节点

$firstChild = $node->getFirstChild();
$lastChild = $node->getLastChild();

您可以使用以下方法获取节点的子节点

$parent = $node->getParent();

遍历树

$children = $node->getChildren();

getChildren() 方法仅返回直接后代。如果您想获取所有后代,请使用 getDescendants() 方法。

您可以通过以下方法获取节点的后代或祖先:

$descendants = $node->getDescendants();
$ancestors = $node->getAncestors();

有时您可能只想获取子节点或后代的数量。您可以使用以下方法来完成此操作:

$numChildren = $node->getNumberChildren();
$numDescendants = $node->getNumberDescendants();

getDescendants() 方法接受一个参数,您可以使用该参数来指定结果分支的深度。例如,getDescendants(1) 仅检索直接后代(位于1级以下的后代,与 getChildren() 相同)。

渲染简单树

$tree = $nsm->fetchTreeAsArray(1);

foreach ($tree as $node) {
    echo str_repeat('&nbsp;&nbsp;', $node->getLevel()) . $node . "<br>";
}

高级用法

前几节已解释了Doctrine嵌套集实现的基礎用法。本节将进一步阐述。

获取带关系的树

如果您是一名要求严格的软件开发人员,这个问题可能已经出现在您的脑海中:“我如何获取带有相关数据的树/分支?”简单的例子:您想显示一个分类树,但您还希望显示每个分类的相关数据,例如该分类中最热销产品的详细信息。像前几节那样获取树,并在遍历树时简单地访问关系是可能的,但会产生大量的不必要的数据库查询。幸运的是,Manager和一些嵌套集实现的灵活性已经为您提供了帮助。嵌套集实现使用 QueryBuilder 对象来处理所有的数据库工作。通过为您提供访问嵌套集实现的基礎查询构建器的权限,您可以在使用嵌套集的同时释放 QueryBuilder 的全部力量。

$qb = $em->createQueryBuilder();
$qb->select('c.name, p.name, m.name')
    ->from('Category', 'c')
    ->leftJoin('c.HottestProduct', 'p')
    ->leftJoin('p.Manufacturer', 'm');

现在我们需要将上述查询设置为树的基礎查询

$nsm->getConfiguration()->setBaseQueryBuilder($qb);
$tree = $nsm->fetchTree(1);

就是这样,所有所需的带相关数据的树,都在一个查询中。

如果您没有设置自己的基礎查询,系统将为您自动创建一个内部查询。

完成操作后,将基礎查询重置为正常是一个好主意

$nsm->getConfiguration()->resetBaseQueryBuilder();

事务

当使用 NodeWrapper 中的方法修改树时,每个方法都会立即执行。这与处理正常Doctrine2实体不同,其中更改通过EntityManager排队,直到调用 flush 才会执行。

如果您正在执行多个更改,建议将这些更改包裹在事务中

$em->getConnection()->beginTransaction();
try {

    $root = $nsm->createRoot(new Category('Root'));
    $root->addChild(new Category('Child 1'));
    $root->addChild(new Category('Child 2'));

    $em->getConnection()->commit();
} catch (Exception $e) {
    $em->close();
    $em->getConnection()->rollback();
    throw $e;
}

自定义左、右和根字段

NestedSet需要您在实体类中包含左、右和根字段。默认情况下,NestedSet期望这些字段分别命名为lft、rgt和root。您可以通过管理器配置来自定义这些字段的名称

$config = new Config($em, 'Entity\Category');
$config->setLeftFieldName('nsLeft');
$config->setRightFieldName('nsRight');
$config->setRootFieldName('nsRoot');
$nsm = new Manager($config);

结论

NestedSet使得在Doctrine2中管理层次数据变得快速且简单。