ece2/hyperf-ext-nestedset

Hyperf的嵌套集模型

v1.0.1 2023-06-03 16:16 UTC

This package is auto-updated.

Last update: 2024-10-03 19:10:18 UTC


README

这是一个用于在关系型数据库中操作树形数据的Laravel 4-8的包。

  • Laravel 5.7, 5.8, 6.0, 7.0, 8.0自v5版本开始支持
  • Laravel 5.5, 5.6自v4.3版本开始支持
  • Laravel 5.2, 5.3, 5.4自v4版本开始支持
  • Laravel 5.1在v3版本中支持
  • Laravel 4在v2版本中支持

虽然这个项目完全免费使用,但我感激任何支持!

内容

什么是嵌套集?

嵌套集或嵌套集模型是一种有效存储关系型表中的层次数据的办法。来自维基百科

嵌套集模型是对节点按照树遍历的顺序进行编号,遍历每个节点两次,按访问顺序分配数字,并在两次访问时分配。这为每个节点留下两个数字,这两个数字作为两个属性存储。查询变得便宜:可以通过比较这些数字来测试层次结构成员资格。更新需要重新编号,因此代价较高。

应用

当树很少更新时,NSM表现出良好的性能。它调整以快速获取相关节点。它非常适合构建多级菜单或商店类别。

文档

假设我们有一个模型Category;一个$node变量是这个模型的实例,是我们正在操作的节点。它可以是新的模型或来自数据库的模型。

关系

节点有以下关系,这些关系是完全功能性的,可以 eager 加载

  • 节点属于parent
  • 节点有多个children
  • 节点有多个ancestors
  • 节点有多个descendants

插入节点

移动和插入节点包括多个数据库查询,因此强烈建议使用事务。

重要!从v4.2.0版本开始,事务不会自动启动

另一个重要的注意事项是,结构操作被延迟,直到你在模型上调用save(某些方法隐式调用save并返回操作的布尔结果)。

如果模型成功保存,并不意味着节点已移动。如果你的应用程序依赖于节点是否实际改变了位置,请使用hasMoved方法

if ($node->save()) {
    $moved = $node->hasMoved();
}

创建节点

当你简单创建一个节点时,它将被添加到树的末尾

Category::create($attributes); // Saved as root
$node = new Category($attributes);
$node->save(); // Saved as root

在这种情况下,该节点被视为一个,这意味着它没有父节点。

从现有节点创建根节点

// #1 Implicit save
$node->saveAsRoot();

// #2 Explicit save
$node->makeRoot()->save();

节点将被添加到树的末尾。

附加和前置到指定的父节点

如果你想使节点成为其他节点的子节点,你可以将其作为最后一个或第一个子节点。

以下示例中,$parent是某个现有节点。

有几种方法可以添加节点

// #1 Using deferred insert
$node->appendToNode($parent)->save();

// #2 Using parent node
$parent->appendNode($node);

// #3 Using parent's children relationship
$parent->children()->create($attributes);

// #5 Using node's parent relationship
$node->parent()->associate($parent)->save();

// #6 Using the parent attribute
$node->parent_id = $parent->id;
$node->save();

// #7 Using static method
Category::create($attributes, $parent);

只有几种方法可以前置

// #1
$node->prependToNode($parent)->save();

// #2
$parent->prependNode($node);

在指定的节点之前或之后插入

你可以使用以下方法使$node成为$neighbor节点的邻居

$neighbor必须存在,目标节点可以是新的。如果目标节点存在,它将被移动到新位置,并且如果需要,父节点将改变。

# Explicit save
$node->afterNode($neighbor)->save();
$node->beforeNode($neighbor)->save();

# Implicit save
$node->insertAfterNode($neighbor);
$node->insertBeforeNode($neighbor);

从数组构建树

在节点上使用静态方法 create 时,它会检查属性是否包含 children 键。如果包含,则会递归地创建更多节点。

$node = Category::create([
    'name' => 'Foo',

    'children' => [
        [
            'name' => 'Bar',

            'children' => [
                [ 'name' => 'Baz' ],
            ],
        ],
    ],
]);

$node->children 现在包含已创建的子节点列表。

从数组重建树

您可以轻松地重建树。这对于大量更改树的结构非常有用。

Category::rebuildTree($data, $delete);

$data 是节点数组

$data = [
    [ 'id' => 1, 'name' => 'foo', 'children' => [ ... ] ],
    [ 'name' => 'bar' ],
];

为名为 foo 的节点指定了 id,这意味着现有节点将被填充并保存。如果节点不存在,将抛出 ModelNotFoundException。此外,此节点还指定了 children,它也是一个节点数组;它们将以相同的方式处理并保存为 foo 节点的子节点。

节点 bar 没有指定主键,因此将创建它。

$delete 显示是否删除已存在但不在 $data 中的节点。默认情况下,不会删除节点。

重建子树

从 4.2.8 版本开始,您可以重建子树

Category::rebuildSubtree($root, $data);

这限制了树重建仅限于 $root 节点的后代。

检索节点

在某些情况下,我们将使用一个 $id 变量,它是目标节点的 id。

祖先和后代

祖先构成从节点到其父节点的链。对于显示当前类别的面包屑非常有用。

后代是子树中的所有节点,即节点的子节点、子节点的子节点等。

祖先和后代都可以使用 eager loading 载入。

// Accessing ancestors
$node->ancestors;

// Accessing descendants
$node->descendants;

可以使用自定义查询加载祖先和后代

$result = Category::ancestorsOf($id);
$result = Category::ancestorsAndSelf($id);
$result = Category::descendantsOf($id);
$result = Category::descendantsAndSelf($id);

在大多数情况下,您需要按级别对祖先进行排序

$result = Category::defaultOrder()->ancestorsOf($id);

可以 eager loading 载入祖先集合

$categories = Category::with('ancestors')->paginate(30);

// in view for breadcrumbs:
@foreach($categories as $i => $category)
    <small>{{ $category->ancestors->count() ? implode(' > ', $category->ancestors->pluck('name')->toArray()) : 'Top Level' }}</small><br>
    {{ $category->name }}
@endforeach

兄弟节点

兄弟节点是具有相同父节点的节点。

$result = $node->getSiblings();

$result = $node->siblings()->get();

仅获取下一个兄弟节点

// Get a sibling that is immediately after the node
$result = $node->getNextSibling();

// Get all siblings that are after the node
$result = $node->getNextSiblings();

// Get all siblings using a query
$result = $node->nextSiblings()->get();

仅获取上一个兄弟节点

// Get a sibling that is immediately before the node
$result = $node->getPrevSibling();

// Get all siblings that are before the node
$result = $node->getPrevSiblings();

// Get all siblings using a query
$result = $node->prevSiblings()->get();

从其他表获取相关模型

想象一下,每个分类 has many 商品。即建立了 HasMany 关系。如何获取 $category 及其所有后代的商品?很简单!

// Get ids of descendants
$categories = $category->descendants()->pluck('id');

// Include the id of category itself
$categories[] = $category->getKey();

// Get goods
$goods = Goods::whereIn('category_id', $categories)->get();

包含节点深度

如果您需要知道节点位于哪个级别

$result = Category::withDepth()->find($id);

$depth = $result->depth;

根节点将位于级别 0。根节点的子节点将具有级别 1,等等。

要获取指定级别的节点,可以应用 having 约束

$result = Category::withDepth()->having('depth', '=', 1)->get();

重要! 在数据库严格模式下,这将不起作用

默认排序

所有节点都严格内部组织。默认情况下,不应用任何排序,因此节点可能会以随机顺序出现,这不会影响树显示。您可以按字母或其他索引对节点进行排序。

但在某些情况下,层次结构排序是必不可少的。它对于检索祖先很有用,也可以用于对菜单项进行排序。

要应用树排序,请使用 defaultOrder 方法

$result = Category::defaultOrder()->get();

您可以以相反的顺序获取节点

$result = Category::reversed()->get();

要移动节点在父节点内的位置以影响默认排序

$bool = $node->down();
$bool = $node->up();

// Shift node by 3 siblings
$bool = $node->down(3);

操作的结果是表示节点是否更改其位置的布尔值。

约束

可以应用于查询构建器的各种约束

  • whereIsRoot() 以获取仅根节点;
  • hasParent() 以获取非根节点;
  • whereIsLeaf() 以获取仅叶子节点;
  • hasChildren() 以获取非叶子节点;
  • whereIsAfter($id) 以获取具有指定 id 的节点之后的所有节点(而不仅仅是兄弟节点);
  • whereIsBefore($id) 以获取具有指定 id 的节点之前的所有节点。

后代约束

$result = Category::whereDescendantOf($node)->get();
$result = Category::whereNotDescendantOf($node)->get();
$result = Category::orWhereDescendantOf($node)->get();
$result = Category::orWhereNotDescendantOf($node)->get();
$result = Category::whereDescendantAndSelf($id)->get();

// Include target node into result set
$result = Category::whereDescendantOrSelf($node)->get();

祖先约束

$result = Category::whereAncestorOf($node)->get();
$result = Category::whereAncestorOrSelf($id)->get();

$node 可以是模型的 primary key 或模型实例。

构建树

在获取一组节点后,您可以将它转换为树。例如

$tree = Category::get()->toTree();

这将填充集合中每个节点上的parentchildren关系,您可以使用递归算法渲染树。

$nodes = Category::get()->toTree();

$traverse = function ($categories, $prefix = '-') use (&$traverse) {
    foreach ($categories as $category) {
        echo PHP_EOL.$prefix.' '.$category->name;

        $traverse($category->children, $prefix.'-');
    }
};

$traverse($nodes);

这将输出类似以下内容

- Root
-- Child 1
--- Sub child 1
-- Child 2
- Another root
构建扁平树

此外,您还可以构建一个扁平树:一个节点列表,其中子节点紧接在其父节点之后。当您获取具有自定义顺序(例如按字母顺序)的节点且不想使用递归遍历节点时,这很有用。

$nodes = Category::get()->toFlatTree();

上一个示例将输出

Root
Child 1
Sub child 1
Child 2
Another root
获取子树

有时您不需要加载整个树,只需特定节点的子树。以下示例展示了这一点

$root = Category::descendantsAndSelf($rootId)->toTree()->first();

在一个查询中,我们获取子树的根节点及其所有可通过children关系访问的后代。

如果您不需要$root节点本身,则执行以下操作

$tree = Category::descendantsOf($rootId)->toTree($rootId);

删除节点

要删除节点

$node->delete();

重要!该节点有任何后代也将被删除!

重要!节点必须作为模型进行删除,不要尝试使用以下查询之类的查询删除它们

Category::where('id', '=', $id)->delete();

这将破坏树!

SoftDeletes特征受到支持,也适用于模型级别。

辅助方法

检查节点是否是其他节点的后代

$bool = $node->isDescendantOf($parent);

检查节点是否是根节点

$bool = $node->isRoot();

其他检查

  • $node->isChildOf($other);
  • $node->isAncestorOf($other);
  • $node->isSiblingOf($other);
  • $node->isLeaf()

检查一致性

您可以检查树是否损坏(即存在一些结构错误)

$bool = Category::isBroken();

可以获取错误统计信息

$data = Category::countErrors();

它将返回一个数组,具有以下键

  • oddness -- 错误的lftrgt值的节点数量
  • duplicates -- 具有相同lftrgt值的节点数量
  • wrong_parent -- 具有无效parent_id值的节点数量,该值不对应于lftrgt
  • missing_parent -- 指向不存在节点的parent_id的节点数量

修复树

从v3.1版本开始,现在可以修复树。使用parent_id列的继承信息,为每个节点设置适当的_lft_rgt值。

Node::fixTree();

作用域

假设您有一个Menu模型和一个MenuItems。在这些模型之间设置了单对多关系。MenuItem具有menu_id属性,用于将模型连接起来。MenuItem采用了嵌套集。很明显,您会希望根据menu_id属性分别处理每个树。为此,您需要将此属性指定为作用域属性。

protected function getScopeAttributes()
{
    return [ 'menu_id' ];
}

但是,现在,为了执行一些自定义查询,您需要提供用于作用域的属性

MenuItem::scoped([ 'menu_id' => 5 ])->withDepth()->get(); // OK
MenuItem::descendantsOf($id)->get(); // WRONG: returns nodes from other scope
MenuItem::scoped([ 'menu_id' => 5 ])->fixTree(); // OK

当使用模型实例请求节点时,会根据该模型的属性自动应用作用域

$node = MenuItem::findOrFail($id);

$node->siblings()->withDepth()->get(); // OK

使用实例获取作用域查询构建器

$node->newScopedQuery();

作用域和预加载

始终在预加载时使用作用域查询

MenuItem::scoped([ 'menu_id' => 5])->with('descendants')->findOrFail($id); // OK
MenuItem::with('descendants')->findOrFail($id); // WRONG

要求

  • PHP >= 5.4
  • Laravel >= 4.1

强烈建议使用支持事务的数据库(如MySQL的InnoDB)来保护树免受可能的损坏。

安装

要在终端中安装该包

composer require kalnoy/nestedset

从头开始设置

模式

对于Laravel 5.5及以上版本的用户

Schema::create('table', function (Blueprint $table) {
    ...
    $table->nestedSet();
});

// To drop columns
Schema::table('table', function (Blueprint $table) {
    $table->dropNestedSet();
});

对于早期版本的Laravel

...
use Ece2\HyperfExtNestedset\NestedSet;

Schema::create('table', function (Blueprint $table) {
    ...
    NestedSet::columns($table);
});

要删除列

...
use Ece2\HyperfExtNestedset\NestedSet;

Schema::table('table', function (Blueprint $table) {
    NestedSet::dropColumns($table);
});

模型

您的模型应该使用Ece2\HyperfExtNestedset\NodeTrait特征来启用嵌套集

use Ece2\HyperfExtNestedset\NodeTrait;

class Foo extends Model {
    use NodeTrait;
}

迁移现有数据

从其他嵌套集扩展迁移

如果您的先前扩展使用不同的列集,您只需在模型类中覆盖以下方法即可

public function getLftName()
{
    return 'left';
}

public function getRgtName()
{
    return 'right';
}

public function getParentIdName()
{
    return 'parent';
}

// Specify parent id attribute mutator
public function setParentAttribute($value)
{
    $this->setParentIdAttribute($value);
}

从基本父级信息迁移

如果你的树包含 parent_id 信息,你需要在你的模式中添加两列

$table->unsignedInteger('_lft');
$table->unsignedInteger('_rgt');

设置好你的模型后,你只需要调整树以填写 _lft_rgt

MyModel::fixTree();

许可

版权所有 (c) 2017 Alexander Kalnoy

任何人获得此软件及其相关文档文件(以下简称“软件”)的副本,均可免费使用软件,不受任何限制,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本的权利,并允许向软件提供方提供软件的人这样做,前提是遵守以下条件

上述版权声明和本许可声明应包含在软件的所有副本或主要部分中。

软件按“原样”提供,不提供任何形式的保证,无论是明示的、暗示的还是基于特定目的的适用性或非侵权性保证。在任何情况下,作者或版权所有者不对任何索赔、损害或其他责任负责,无论此类索赔、损害或其他责任是基于合同、侵权或其他行为,无论是在软件或软件的使用或其他交易中产生的。