imajkumar/laravel-binary-tree

Ayra 是一个用于 Eloquent 模型的嵌套集模式的实现。

dev-master 2023-04-15 05:59 UTC

This package is auto-updated.

Last update: 2024-09-15 08:49:55 UTC


README

适用于 laravel 5.8

要可视化嵌套集的工作方式,可以想象一个父实体包围了所有子实体,其父实体又包围了它,依此类推。所以这个树

root
  |_ Child 1
    |_ Child 1.1
    |_ Child 1.2
  |_ Child 2
    |_ Child 2.1
    |_ Child 2.2

可以这样可视化

 ___________________________________________________________________
|  Root                                                             |
|    ____________________________    ____________________________   |
|   |  Child 1                  |   |  Child 2                  |   |
|   |   __________   _________  |   |   __________   _________  |   |
|   |  |  C 1.1  |  |  C 1.2 |  |   |  |  C 2.1  |  |  C 2.2 |  |   |
1   2  3_________4  5________6  7   8  9_________10 11_______12 13  14
|   |___________________________|   |___________________________|   |
|___________________________________________________________________|

数字代表左边界和右边界。然后表可能看起来像这样

id | parent_id | lft  | rgt  | depth | data
 1 |           |    1 |   14 |     0 | root
 2 |         1 |    2 |    7 |     1 | Child 1
 3 |         2 |    3 |    4 |     2 | Child 1.1
 4 |         2 |    5 |    6 |     2 | Child 1.2
 5 |         1 |    8 |   13 |     1 | Child 2
 6 |         5 |    9 |   10 |     2 | Child 2.1
 7 |         5 |   11 |   12 |     2 | Child 2.2

要获取一个 节点的所有子节点,你

SELECT * WHERE lft IS BETWEEN parent.lft AND parent.rgt

要获取子节点的数量,它是

(right - left - 1)/2

要获取一个节点及其所有祖先节点直到根节点,你是

SELECT * WHERE node.lft IS BETWEEN lft AND rgt

如你所见,在普通树上通常是递归且速度极慢的查询,在嵌套树上却突然变得非常快。很酷,不是吗?

创建根节点

默认情况下,所有节点都创建为根节点

$root = Category::create(['name' => 'Root category']);

或者,你可能需要将现有的节点 转换为 根节点

$node->makeRoot();

你也可以将其 parent_id 列设置为 NULL 以实现相同的行为

// This works the same as makeRoot()
$node->parent_id = null;
$node->save();

插入节点

// Directly with a relation
$child1 = $root->children()->create(['name' => 'Child 1']);

// with the `makeChildOf` method
$child2 = Category::create(['name' => 'Child 2']);
$child2->makeChildOf($root);

删除节点

$child1->delete();

被删除节点的后代也将被删除,并且所有 lftrgt 边界将重新计算。请注意,目前,对于后代将不会触发 deletingdeleted 模型事件。

获取节点的嵌套级别

getLevel() 方法将返回节点的当前嵌套级别或深度。

$node->getLevel() // 0 when root

移动节点

Baum 提供了几个用于移动节点的方法

  • moveLeft():找到左兄弟并将其移动到左侧。
  • moveRight():找到右兄弟并将其移动到右侧。
  • moveToLeftOf($otherNode):移动到 ... 的左侧节点
  • moveToRightOf($otherNode):移动到 ... 的右侧节点
  • makeNextSiblingOf($otherNode):是 moveToRightOf 的别名。
  • makeSiblingOf($otherNode):是 makeNextSiblingOf 的别名。
  • makePreviousSiblingOf($otherNode):是 moveToLeftOf 的别名。
  • makeChildOf($otherNode):将节点变为 ... 的子节点
  • makeFirstChildOf($otherNode):将节点变为 ... 的第一个子节点
  • makeLastChildOf($otherNode):是 makeChildOf 的别名。
  • makeRoot():将当前节点变为根节点。

例如

$root = Creatures::create(['name' => 'The Root of All Evil']);

$dragons = Creatures::create(['name' => 'Here Be Dragons']);
$dragons->makeChildOf($root);

$monsters = new Creatures(['name' => 'Horrible Monsters']);
$monsters->save();

$monsters->makeSiblingOf($dragons);

$demons = Creatures::where('name', '=', 'demons')->first();
$demons->moveToLeftOf($dragons);

向你的节点提问

你可以向 Baum 节点提出一些问题

  • isRoot():如果这是一个根节点,则返回 true。
  • isLeaf():如果这是一个叶子节点(分支的末尾),则返回 true。
  • isChild():如果这是一个子节点,则返回 true。
  • isDescendantOf($other):如果节点是另一个的子节点,则返回 true。
  • isSelfOrDescendantOf($other):如果节点是自身或子节点,则返回 true。
  • isAncestorOf($other):如果节点是另一个的祖先,则返回 true。
  • isSelfOrAncestorOf($other):如果节点是自身或祖先,则返回 true。
  • equals($node):当前节点实例等于另一个。
  • insideSubtree($node):检查给定的节点是否在由左和右索引定义的子树中。
  • inSameScope($node):如果给定的节点与当前节点在相同的作用域中,则返回 true。也就是说,如果 每个scoped 属性中的列在两个节点中都有相同的值。

使用之前的示例中的节点

$demons->isRoot(); // => false

$demons->isDescendantOf($root) // => true

关系

为您的节点提供两个自引用的Eloquent关系:parentchildren

$parent = $node->parent()->get();

$children = $node->children()->get();

根和叶作用域

提供了一些非常基本的查询作用域,用于访问根节点和叶节点

// Query scope which targets all root nodes
Category::roots()

// All leaf nodes (nodes at the end of a branch)
Category:allLeaves()

您可能也只对第一个根节点感兴趣

$firstRootNode = Category::root();

访问祖先/后代链

有几个方法可以用来访问嵌套集树中节点的祖先/后代链。需要记住的是,它们以两种方式提供

首先作为查询作用域,返回一个Illuminate\Database\Eloquent\Builder实例以继续查询。要从这些作用域中获取实际结果,请记住调用get()first()

  • ancestorsAndSelf():目标包括当前在内的所有祖先链节点。

  • ancestors():查询不包括当前在内的祖先链节点。

  • siblingsAndSelf():实例作用域,目标为父节点的所有子节点,包括自身。

  • siblings():实例作用域,目标为父节点的所有子节点,除了自身。

  • leaves():实例作用域,目标为所有没有子节点的嵌套子节点。

  • descendantsAndSelf():作用域,目标为自己及其所有嵌套子节点。

  • descendants():所有子节点和嵌套子节点集。

  • immediateDescendants():所有子节点集(非递归)。

  • getRoot():返回从当前节点开始的根节点。

  • getAncestorsAndSelf():检索包括当前节点的所有祖先链。

  • getAncestorsAndSelfWithoutRoot():包括当前节点但在根节点之外的所有祖先。

  • getAncestors():从数据库中获取不包括当前节点的所有祖先链。

  • getAncestorsWithoutRoot():不包括当前节点和根节点的所有祖先。

  • getSiblingsAndSelf():获取包括自身在内的所有父节点子节点。

  • getSiblings():返回所有父节点子节点,除了自身。

  • getLeaves():返回所有没有子节点的嵌套子节点。

  • getDescendantsAndSelf():检索所有嵌套子节点和自身。

  • getDescendants():检索所有子节点和嵌套子节点。

  • getImmediateDescendants():检索所有子节点(非递归)。

以下是一个迭代节点后代(假设有一个名称属性)的简单示例

$node = Category::where('name', '=', 'Books')->first();

foreach($node->getDescendantsAndSelf() as $descendant) {
  echo "{$descendant->name}";
}

限制返回子节点的级别

在某些情况下,如果层次深度很大,可能希望限制返回的子节点级别数(深度)。您可以通过使用limitDepth查询作用域来实现这一点。

以下片段将获取当前节点的后代,最多5个深度级别以下

$node->descendants()->limitDepth(5)->get();

类似地,您可以通过提供所需深度限制作为第一个参数,使用getDescendantsgetDescendantsAndSelf方法来限制后代级别。

// This will work without depth limiting
// 1. As usual
$node->getDescendants();
// 2. Selecting only some attributes
$other->getDescendants(array('id', 'parent_id', 'name'));
...
// With depth limiting
// 1. A maximum of 5 levels of children will be returned
$node->getDescendants(5);
// 2. A max. of 5 levels of children will be returned selecting only some attrs
$other->getDescendants(5, array('id', 'parent_id', 'name'));

自定义排序列

默认情况下,所有结果按lft索引列值排序,以保证一致性。

如果您想更改此默认行为,您需要在模型中指定要用于排序结果的列名,如下所示

protected $orderColumn = 'name';

导出层次树

扩展默认的Eloquent\Collection类,并为其提供toHierarchy方法,该方法返回一个表示查询树的嵌套集合。

将完整的树层次结构检索到一个常规的Collection对象中,其子节点正确嵌套,就像这样

$tree = Category::where('name', '=', 'Books')->first()->getDescendantsAndSelf()->toHierarchy();

模型事件:movingmoved

模型触发以下事件:movingmoved,每当节点在嵌套集树中移动时。这允许您在节点移动过程中挂钩到这些点。与正常的Eloquent模型事件一样,如果moving事件返回false,则移动操作将被取消。

将事件与模型绑定推荐的方式是通过使用模型的boot方法

class Category extends Ayra\Node {

  public static function boot() {
    parent::boot();

    static::moving(function($node) {
      // Before moving the node this function will be called.
    });

    static::moved(function($node) {
      // After the move operation is processed this function will be
      // called.
    });
  }

}

作用域支持

提供了一个简单的方法来实现嵌套集合的“作用域”功能,限制了我们认为属于嵌套集合树的部分。这应该允许在同一个数据库表中存在多个嵌套集合树。

要使用作用域功能,您可以在您的子类中重写scoped模型属性。此属性应包含一个数组,包含用于限制嵌套集合查询的列名(数据库字段)。

class Category extends Ayra\Node {
  ...
  protected $scoped = array('company_id');
  ...
}

在上一个示例中,company_id有效地限制了(或“作用域”)一个嵌套集合树。因此,对于该字段的每个值,我们可能能够构建一个完全不同的树。

$root1 = Category::create(['name' => 'R1', 'company_id' => 1]);
$root2 = Category::create(['name' => 'R2', 'company_id' => 2]);

$child1 = Category::create(['name' => 'C1', 'company_id' => 1]);
$child2 = Category::create(['name' => 'C2', 'company_id' => 2]);

$child1->makeChildOf($root1);
$child2->makeChildOf($root2);

$root1->children()->get(); // <- returns $child1
$root2->children()->get(); // <- returns $child2

所有询问或遍历嵌套集合树的函数都将使用scoped属性(如果提供)。

请注意,目前不支持在作用域之间移动节点。

验证

::isValidNestedSet()静态方法允许您检查您的基础树结构是否正确。它主要检查以下三件事

  • 检查绑定索引lftrgt是否不为空,rgt值大于lft,并且在父节点(如果设置)的范围内。
  • 确保没有重复的lftrgt列值。
  • 由于第一个检查实际上并没有检查根节点,因此请检查每个根节点是否具有在其子节点范围内的lftrgt索引。

所有检查都是作用域感知的,如果需要,将单独检查每个作用域。

示例用法,给定一个Category节点类

Category::isValidNestedSet()
=> true

树重建

支持通过::rebuild()静态方法完全重建(或重新索引)整个树结构。

此方法将重新索引所有lftrgtdepth列值,仅从父节点与子节点关系的角度检查您的树。这意味着您只需要一个正确填充的parent_id列,并且将尽力重新计算其余部分。

当索引值出现严重问题时,这非常有用,或者当需要从另一个实现(可能有一个parent_id列)转换时,这可能非常有用。

此操作也是作用域感知的,如果定义了作用域,将单独重建所有作用域。

简单示例用法,给定一个Category节点类

Category::rebuild()

有效的树(根据isValidNestedSet方法)将不会被重建。要强制索引重建过程,只需将重建方法的第一参数设置为true

Category::rebuild(true);

软删除

对软删除操作提供了有限的支持。我所说的有限是指测试仍然有限,并且软删除功能将在框架即将推出的4.2版本中发生变化,因此请谨慎使用此功能。

目前,您可以考虑一个restore()操作是安全的

  • 恢复一个叶节点
  • 恢复一个父节点未被软删除的整个子树

种子/批量赋值

由于嵌套集合结构通常涉及许多方法调用以构建层次结构(这会导致多个数据库查询),提供了两个方便的方法,可以将提供的节点属性数组映射到数据库中。

  • buildTree($nodeList):(静态方法) 将提供的节点属性数组映射到数据库中。
  • makeTree($nodeList):(实例方法) 使用当前节点实例作为提供的子树的父节点,将提供的节点属性数组映射到数据库中。

这两个方法将在主键未提供时创建新节点,如果提供主键,则更新创建,并删除所有不在影响作用域中的节点。请理解,对于buildTree静态方法,影响作用域是整个嵌套集合树,对于makeTree实例方法,是当前节点的所有后代。

例如,想象一下我们想要将以下类别层次结构映射到我们的数据库中

  • 电视 & 家庭影院
  • 平板电脑 & 电子阅读器
  • 电脑
    • 笔记本电脑
      • PC 笔记本
      • Macbook(Air/Pro)
    • 台式机
    • 显示器
  • 手机

以下代码可以轻松实现这一功能

$categories = [
  ['id' => 1, 'name' => 'TV & Home Theather'],
  ['id' => 2, 'name' => 'Tablets & E-Readers'],
  ['id' => 3, 'name' => 'Computers', 'children' => [
    ['id' => 4, 'name' => 'Laptops', 'children' => [
      ['id' => 5, 'name' => 'PC Laptops'],
      ['id' => 6, 'name' => 'Macbooks (Air/Pro)']
    ]],
    ['id' => 7, 'name' => 'Desktops'],
    ['id' => 8, 'name' => 'Monitors']
  ]],
  ['id' => 9, 'name' => 'Cell Phones']
];

Category::buildTree($categories) // => true

之后,我们可以根据需要更新层次结构

$categories = [
  ['id' => 1, 'name' => 'TV & Home Theather'],
  ['id' => 2, 'name' => 'Tablets & E-Readers'],
  ['id' => 3, 'name' => 'Computers', 'children' => [
    ['id' => 4, 'name' => 'Laptops', 'children' => [
      ['id' => 5, 'name' => 'PC Laptops'],
      ['id' => 6, 'name' => 'Macbooks (Air/Pro)']
    ]],
    ['id' => 7, 'name' => 'Desktops', 'children' => [
      // These will be created
      ['name' => 'Towers Only'],
      ['name' => 'Desktop Packages'],
      ['name' => 'All-in-One Computers'],
      ['name' => 'Gaming Desktops']
    ]]
    // This one, as it's not present, will be deleted
    // ['id' => 8, 'name' => 'Monitors'],
  ]],
  ['id' => 9, 'name' => 'Cell Phones']
];

Category::buildTree($categories); // => true

makeTree 实例方法的工作方式类似。唯一的不同之处在于它只会对调用节点实例的 后代 执行操作。

现在,想象一下我们已经在数据库中有了以下层次结构

  • 电子产品
  • 健康健身 & 美容
  • 小家电
  • 大家电

如果我们执行以下代码

$children = [
  ['name' => 'TV & Home Theather'],
  ['name' => 'Tablets & E-Readers'],
  ['name' => 'Computers', 'children' => [
    ['name' => 'Laptops', 'children' => [
      ['name' => 'PC Laptops'],
      ['name' => 'Macbooks (Air/Pro)']
    ]],
    ['name' => 'Desktops'],
    ['name' => 'Monitors']
  ]],
  ['name' => 'Cell Phones']
];

$electronics = Category::where('name', '=', 'Electronics')->first();
$electronics->makeTree($children); // => true

将得到以下结果

  • 电子产品
    • 电视 & 家庭影院
    • 平板电脑 & 电子阅读器
    • 电脑
      • 笔记本电脑
        • PC 笔记本
        • Macbook(Air/Pro)
      • 台式机
      • 显示器
    • 手机
  • 健康健身 & 美容
  • 小家电
  • 大家电

更新和删除子树中的节点的方式相同。

其他/实用函数

节点提取查询范围

提供了一些查询范围,可以用于从当前结果集中提取(删除)选定的节点。

  • withoutNode(node):从当前结果集中提取指定的节点。
  • withoutSelf():从当前结果集中提取自身。
  • withoutRoot():从结果集中提取当前根节点。
$node = Category::where('name', '=', 'Some category I do not want to see.')->first();

$root = Category::where('name', '=', 'Old boooks')->first();
var_dump($root->descendantsAndSelf()->withoutNode($node)->get());
... // <- This result set will not contain $node

获取嵌套列表的列值

::getNestedList() 静态方法返回一个键值对数组,指示节点深度。对于填充 select 元素等很有用。

它期望返回列名,可选:用作数组键的列(如果没有提供,则使用 id)和/或分隔符

public static function getNestedList($column, $key = null, $seperator = ' ');

一个示例用例

$nestedList = Category::getNestedList('name');
// $nestedList will contain an array like the following:
// array(
//   1 => 'Root 1',
//   2 => ' Child 1',
//   3 => ' Child 2',
//   4 => '  Child 2.1',
//   5 => ' Child 3',
//   6 => 'Root 2'
// );

贡献

考虑过贡献吗?也许你发现了一些严重的错误?这是个好消息!

  1. 分支并克隆项目: git clone git@github.com:your-username/baum.git
  2. 运行测试并确保它们通过你的设置: phpunit
  3. 创建你的错误修复/功能分支,并开始编写代码。为你的更改添加测试。
  4. 确保所有测试仍然通过: phpunit
  5. 将更改推送到你的分支并提交新的拉取请求。

许可

我刚刚为 laravel 5.8 优化的这个从 Baum laravel 包分支。感谢 Baum。Baum 根据 MIT 许可协议 许可(有关详细信息,请参阅 LICENSE 文件)。