该包已被废弃且不再维护。未建议替代包。

Baum是实现嵌套集合模式的Eloquent模型。

1.3 2019-04-02 14:22 UTC

README

etrepat/baum分叉 - 继续开发并修复Laravel 5.x的失败单元测试(目前支持Laravel 5.2 - 5.4)

2.0版本支持Laravel 5.5、特质等正在开发中。请查看feature/2.0分支以获取更多信息。

如果您发现错误,请提交问题并提交一个包含失败单元测试的pull请求

Baum是为Laravel 5的Eloquent ORM实现的嵌套集合模式。

为支持Laravel 4.2.x,请查看1.0.x分支或使用最新的1.0.x标签发布

文档

关于嵌套集合

嵌套集合是一种智能方式实现一个有序的树,允许快速的非递归查询。例如,您可以一次性查询一个节点的所有后代,无论树有多深。缺点是插入/移动/删除需要复杂的SQL,但这由该包在幕后处理!

嵌套集合适用于有序树(例如菜单、商业类别)和必须高效查询的大树(例如线程帖子)。

有关更多信息,请参阅嵌套集合的维基百科条目。此外,这是一篇好的入门教程:http://www.evanpetersen.com/item/nested-sets.html

理论背后的,一个TL;DR版本

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

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

如您所见,在普通树上会导致递归和过慢的查询现在变得非常快。很酷,不是吗?

安装

从 Laravel 5 开始,Baum 就可以与 Laravel 一起使用。您可以通过以下方式将其添加到您的 composer.json 文件中:

"gazsp/baum": "~1.1"

运行 composer install 来安装它。

与大多数 Laravel 5 包一样,接下来您需要注册 Baum 的 服务提供者。要做到这一点,请转到您的 config/app.php 文件,并在 providers 数组中添加以下行

'Baum\Providers\BaumServiceProvider',

入门指南

安装包正确后,开始使用提供的生成器的最简单方法是运行它

php artisan baum:install MODEL

将模型替换为您计划用于嵌套集合模型的类名。

生成器将安装一个迁移文件和一个模型文件到您的应用程序中,这些文件配置为使用 Baum 提供的嵌套集合行为。您应该查看这些文件,因为它们中的每一个都描述了如何进行自定义。

接下来,您可能会运行 artisan migrate 来应用迁移。

模型配置

为了与 Baum 一起工作,您必须确保您的模型类扩展 Baum\Node

这是最简单的方法

class Category extends Baum\Node {

}

这是一个 稍微 复杂的示例,其中列名已定制

class Dictionary extends Baum\Node {

  protected $table = 'dictionary';

  // 'parent_id' column name
  protected $parentColumn = 'parent_id';

  // 'lft' column name
  protected $leftColumn = 'lidx';

  // 'rgt' column name
  protected $rightColumn = 'ridx';

  // 'depth' column name
  protected $depthColumn = 'nesting';

  // guard attributes from mass-assignment
  protected $guarded = array('id', 'parent_id', 'lidx', 'ridx', 'nesting');

}

请记住,显然,列名必须与数据库表中的列名匹配。

迁移配置

您必须确保支持您的 Baum 模型的数据库表具有以下列

  • parent_id:对父级(int)的引用
  • lft:左索引边界(int)
  • rgt:右索引边界(int)
  • depth:深度或嵌套级别(int)

以下是一个示例迁移文件

class Category extends Migration {

  public function up() {
    Schema::create('categories', function(Blueprint $table) {
      $table->increments('id');

      $table->integer('parent_id')->nullable();
      $table->integer('lft')->nullable();
      $table->integer('rgt')->nullable();
      $table->integer('depth')->nullable();

      $table->string('name', 255);

      $table->timestamps();
    });
  }

  public function down() {
    Schema::drop('categories');
  }

}

您可以在迁移和模型中自由修改列名。

使用方法

配置模型并运行迁移后,您现在可以使用 Baum 与模型一起使用。以下是一些示例。

创建根节点

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

$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。
  • isChildOf($other):如果此节点是其他节点的子节点,则返回 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

关系

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

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

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

根和叶子作用域

Baum 提供了一些基本的查询作用域来访问根和叶子节点。

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

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

你可能还只对第一个根节点感兴趣

$firstRootNode = Category::root();

访问血统/世系链

Baum 提供了多种方法来访问嵌套集合树中节点的血统/世系链。要注意的是,它们以两种方式提供:

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

  • ancestorsAndSelf():目标为包括当前节点在内的所有祖先链节点。
  • ancestors():查询不包括当前节点的祖先链节点。
  • siblingsAndSelf():实例作用域,目标为父节点的所有子节点,包括自身。
  • siblings():实例作用域,目标为父节点的所有子节点,除了自身。
  • leaves():实例作用域,目标为其嵌套子节点中不包含子节点的所有节点。
  • descendantsAndSelf():作用域,目标为自己及其所有嵌套子节点。
  • descendants():所有子节点及嵌套子节点集。
  • immediateDescendants():所有子节点集(非递归)。

其次,作为返回实际 Baum\Node 实例的方法(在适当的 Collection 对象内部)

  • 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}";
}

限制返回的子节点级别

在某些情况下,如果层次深度很大,可能需要限制返回的子节点级别(深度)。您可以通过在 Baum 中使用 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'));

自定义排序列

默认情况下,在 Baum 中所有结果都按 lft 索引列的值进行排序,以确保一致性。

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

protected $orderColumn = 'name';

导出层次树

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

将完整的层次树结构检索到具有正确嵌套子节点的常规 Collection 对象中非常简单

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

模型事件:movingmoved

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

挂钩这些事件的推荐方法是使用模型的自定义方法

class Category extends Baum\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.
    });
  }

}

作用域支持

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

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

class Category extends Baum\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() 静态方法允许您检查您的基础树结构是否正确。它主要检查以下3件事情

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

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

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

Category::isValidNestedSet()
=> true

树重建

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

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

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

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

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

Category::rebuild()

不会检查树是否已有效,这意味着重建调用将始终重建树,无论其是否有效。如果您不希望这种行为,当 isValidNestedSet 返回 true 时,不要调用 rebuild。

软删除

使用软删除 / restore() 不推荐,并且如果树在软删除操作后已修改,可能会导致问题。

播种/批量赋值

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

  • 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)
      • 台式机
      • 显示器
    • 手机
  • 健康与美容
  • 小型家电
  • 大型家电

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

杂项/实用函数

节点提取查询范围

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

  • 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 = ' ', $symbol = '');

一个示例用例

$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'
// );

更多信息

您可以在 wiki 中找到有关 Baum 的更多信息、使用示例和/或常见问题。

完成本 README 后,请随时浏览 wiki

https://github.com/etrepat/baum/wiki

贡献

想要贡献吗?也许你发现了一些讨厌的虫子?这是个好消息!

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

请参阅 CONTRIBUTING.md 文件以获取更详细的指南和建议。

许可

Baum 在 MIT 许可证 的条款下授权(有关详细信息,请参阅 LICENSE 文件)。

Estanislau Trepat (etrepat) 编码。我还在 @etrepat 上发推。