无限 / baum
Baum 是为 Eloquent 模型实现的嵌套集合模式。
Requires
- php: >=5.4.0
- illuminate/console: 5.*
- illuminate/database: 5.*
- illuminate/events: 5.*
- illuminate/filesystem: 5.*
- illuminate/support: 5.*
Requires (Dev)
- d11wtq/boris: ~1.0.10
- mockery/mockery: ~0.9
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2024-09-28 20:14:33 UTC
README
Baum 是为 Laravel 5 的 Eloquent ORM 实现的 嵌套集合 模式。
对于 Laravel 4.2.x 兼容性,请查看 1.0.x 分支 或使用最新的 1.0.x 标签版本。
文档
关于嵌套集合
嵌套集合是一种智能的方式来实现一个 有序 的树,它允许进行快速的非递归查询。例如,你可以通过单个查询获取节点的所有子节点,无论树的深度如何。缺点是插入/移动/删除需要复杂的 SQL,但这由该包在幕后处理!
嵌套集合适用于有序树(例如,菜单,商业类别)和必须高效查询的大型树(例如,线式帖子)。
有关嵌套集合的更多信息,请参阅 维基百科条目。此外,这是一个很好的入门教程:http://www.evanpetersen.com/item/nested-sets.html
背后的理论,一个简洁的版本
直观理解嵌套集合工作方式的一个简单方法是想象一个父实体包围着所有子实体,然后是其父实体,等等。所以这个树
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
正如你所看到的,在普通树上递归和过慢的查询突然变得非常快。很酷,不是吗?
安装
Baum 与 Laravel 5 及更高版本兼容。您可以使用以下方式将其添加到您的 composer.json
文件中
"baum/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与您的模型一起使用。以下是几个示例。
- 创建根节点
- 插入节点
- 删除节点
- 获取节点的嵌套级别
- 移动节点
- 向节点提问
- 关系
- 根和叶子作用域
- 访问祖先/后代链
- 限制返回的子节点级别
- 自定义排序列
- 转储层次树
- 模型事件:
moving
和moved
- 作用域支持
- 验证
- 树重建
- 软删除
- 种子/批量赋值
- 杂项/实用函数
创建根节点
默认情况下,所有节点都创建为根节点
$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();
已删除节点的后代也将被删除,并且所有的lft
和rgt
边界将被重新计算。请注意,目前,不会触发后代节点的deleting
和deleted
模型事件。
获取节点的嵌套级别
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
关系
Baum为您的节点提供了两个自引用Eloquent关系:parent
和children
。
$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();
同样,您可以通过提供所需的深度限制作为第一个参数,使用getDescendants
和getDescendantsAndSelf
方法来限制后代层级。
// 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();
模型事件:moving
和 moved
Baum模型在每次节点在嵌套集树中移动时都会触发以下事件:moving
和moved
。这允许您在节点移动过程中挂钩。与正常的Eloquent模型事件一样,如果moving
事件返回false
,则移动操作将被取消。
推荐通过使用模型的启动方法(boot method)来挂钩这些事件。
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提供了一个简单的方法来实现嵌套集合(Nested Set)“范围”限制,这限制了我们将哪些内容视为嵌套集合树的一部分。这应该允许在同一数据库表中存在多个嵌套集合树。
要使用范围功能,您可以在您的子类中覆盖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()
静态方法允许您检查您的基础树结构是否正确。它主要检查以下三件事:
- 检查约束索引
lft
和rgt
是否不为空,rgt
值大于lft
,并且(如果设置)在父节点范围内。 - 没有重复的
lft
和rgt
列值。 - 由于第一个检查实际上没有检查根节点,请检查每个根节点的
lft
和rgt
索引是否在其子节点范围内。
所有检查都是范围感知的,如果需要,将分别检查每个范围。
示例用法,给定一个Category
节点类
Category::isValidNestedSet() => true
树重建
Baum通过::rebuild()
静态方法支持完整的树结构重建(或重新索引)。
此方法将重新索引所有lft
、rgt
和depth
列值,仅从父节点与子节点关系的角度检查您的树。这意味着您只需要一个正确填充的parent_id
列,Baum将尽力重新计算其余部分。
当索引值出了严重问题,或者当转换自另一种实现(可能有一个parent_id
列)时,这可能会非常有用。
此操作也是范围感知的,如果它们被定义,将单独重新构建所有范围。
简单示例用法,给定一个Category
节点类
Category::rebuild()
有效的树(按照isValidNestedSet
方法)将不会被重建。要强制索引重建过程,只需将重建方法中的第一个参数设置为true
。
Category::rebuild(true);
软删除
Baum对软删除操作提供有限的支持。我所说的有限是指测试仍然是有限的,并且即将推出的框架4.2版本的软删除功能正在发生变化,因此请明智地使用此功能。
目前,您可以将安全的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 = ' ');
一个示例用例
$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
贡献
考虑贡献?也许你发现了一些讨厌的bug?这是一个好消息!
- 分支并克隆项目:
git clone git@github.com:your-username/baum.git
。 - 运行测试并确保它们在您的设置中通过:
phpunit
。 - 创建您的bugfix/feature分支,并编写您的更改。为您的更改添加测试。
- 确保所有测试仍然通过:
phpunit
。 - 将更改推送到您的分支并提交新的pull请求。
请参阅CONTRIBUTING.md文件以获取更详细的指南和建议。
许可协议
Baum是在MIT许可协议的条款下许可的(有关详细信息,请参阅LICENSE文件)。
由Estanislau Trepat (etrepat)编写。我还在twitter上@etrepat。