原文连接: http://www.pilishen.com/posts...; 欢迎做客咱们的php&Laravel学习群:109256050
laravel-nestedset是一个关系型数据库遍历树的larvel4-5的插件包php
目录:前端
开始使用node
Nested Set Model 是一种实现有序树的高明的方法,它快速且不须要递归查询,例如无论树有多少层,你能够仅使用一条查询来获取某个节点下的全部的后代,缺点是它的插入、移动、删除须要执行复杂的sql语句,可是这些都在这个插件内处理了!
更多关于详见维基百科!Nested set model 及它中文翻译!嵌套集合模型laravel
强烈建议使用支持事物功能的数据引擎(像MySql的innoDb)来防止可能的数据损坏。算法
在composer.json
文件中加入下面代码:sql
"kalnoy/nestedset": "^4.3",
运行composer install
来安装它。数据库
或者直接在命令行输入json
composer require kalnoy/nestedset
如需安装历史版本请点击更多版本数组
你可使用NestedSet
类的columns
方法来添加有默认名字的字段:app
... use Kalnoy\Nestedset\NestedSet; Schema::create('table', function (Blueprint $table) { ... NestedSet::columns($table); });
删除字段:
... use Kalnoy\Nestedset\NestedSet; Schema::table('table', function (Blueprint $table) { NestedSet::dropColumns($table); });
默认的字段名为:_lft
、_rgt
、parent_id
,源码以下:
public static function columns(Blueprint $table) { $table->unsignedInteger(self::LFT)->default(0); $table->unsignedInteger(self::RGT)->default(0); $table->unsignedInteger(self::PARENT_ID)->nullable(); $table->index(static::getDefaultColumns()); }
你的模型须要使用Kalnoy\Nestedset\NodeTrait
trait 来实现nested sets
use Kalnoy\Nestedset\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();
Node具备如下功能,他们功能彻底且被预加载:
假设咱们有一个Category模型;变量$node是该模型的一个实例是咱们操做的node(节点)。它能够为一个新建立的node或者是从数据库中取出的node
每次插入或者移动一个节点都要执行好几条数据库操做,全部强烈推荐使用transaction.
注意! 对于v4.2.0版本不是自动开启transaction的,另外node的结构化操做须要在模型上手动执行save,可是有些方法会隐性执行save并返回操做后的布尔类型的结果。
当你简单的建立一个node,它会被添加到树的末端。
Category::create($attributes); // 自动save为一个根节点(root)
或者
$node = new Category($attributes); $node->save(); // save为一个根节点(root)
在这里node被设置为root,意味着它没有父节点
// #1 隐性 save $node->saveAsRoot(); // #2 显性 save $node->makeRoot()->save();
若是你想添加子节点,你能够添加为父节点的第一个子节点或者最后一个子节点。
*在下面的例子中, $parent
为已存在的节点
添加到父节点的末端的方法包括:
// #1 使用延迟插入 $node->appendToNode($parent)->save(); // #2 使用父节点 $parent->appendNode($node); // #3 借助父节点的children关系 $parent->children()->create($attributes); // #5 借助子节点的parent关系 $node->parent()->associate($parent)->save(); // #6 借助父节点属性 $node->parent_id = $parent->id; $node->save(); // #7 使用静态方法 Category::create($attributes, $parent);
添加到父节点的前端的方法
// #1 $node->prependToNode($parent)->save(); // #2 $parent->prependNode($node);
你可使用下面的方法来将$node
添加为指定节点$neighbor
的相邻节点
$neighbor
必须存在,$node
能够为新建立的节点,也能够为已存在的,若是$node
为已存在的节点,它将移动到新的位置与$neighbor
相邻,必要时它的父级将改变。
# 显性save $node->afterNode($neighbor)->save(); $node->beforeNode($neighbor)->save(); # 隐性 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' ], ];
上面有一个name
为foo
的节点,它有指定的id
,表明这个已存在的节点将被填充,若是这个节点不存在,就好抛出一个ModelNotFoundException
,另外,这个节点还有children
数组,这个数组也会以相同的方式添加到foo
节点内。bar
节点没有主键,就是不存在,它将会被建立。$delete
表明是否删除数据库中已存在的可是$data
中不存在的数据,默认为不删除。
重建子树
对于4.3.8版本之后你能够重建子树
Category::rebuildSubtree($root, $data);
这将限制只重建$root子树
在某些状况下咱们须要使用变量$id表明目标节点的主键id
Ancestors 建立一个节点的父级链,这对于展现当前种类的面包屑颇有帮助。
Descendants 是一个父节点的全部子节点。
Ancestors和Descendants均可以预加载。
// Accessing ancestors $node->ancestors; // Accessing descendants $node->descendants;
经过自定义的查询加载ancestors和descendants:
$result = Category::ancestorsOf($id); $result = Category::ancestorsAndSelf($id); $result = Category::descendantsOf($id); $result = Category::descendantsAndSelf($id);
大多数状况下,你须要按层级排序:
$result = Category::defaultOrder()->ancestorsOf($id);
祖先集合能够被预加载:
$categories = Category::with('ancestors')->paginate(30); // 视图模板中面包屑: @foreach($categories as $i => $category) <small> $category->ancestors->count() ? implode(' > ', $category->ancestors->pluck('name')->toArray()) : 'Top Level' </small><br> $category->name @endforeach
将祖先的name
所有取出后转换为数组,在用>拼接为字符串输出。
有相同父节点的节点互称为兄弟节点
$result = $node->getSiblings(); $result = $node->siblings()->get();
获取相邻的后面兄弟节点:
// 获取相邻的下一个兄弟节点 $result = $node->getNextSibling(); // 获取后面的全部兄弟节点 $result = $node->getNextSiblings(); // 使用查询得到全部兄弟节点 $result = $node->nextSiblings()->get();
获取相邻的前面兄弟节点:
// 获取相邻的前一个兄弟节点 $result = $node->getPrevSibling(); // 获取前面的全部兄弟节点 $result = $node->getPrevSiblings(); // 使用查询得到全部兄弟节点 $result = $node->prevSiblings()->get();
假设每个category has many goods, 而且 hasMany 关系已经创建,怎么样简单的获取$category 和它全部后代下全部的goods?
// 获取后代的id $categories = $category->descendants()->pluck('id'); // 包含Category自己的id $categories[] = $category->getKey(); // 得到goods $goods = Goods::whereIn('category_id', $categories)->get();
若是你须要知道node的出入那一层级:
$result = Category::withDepth()->find($id); $depth = $result->depth;
根节点(root)是第0层(level 0),root的子节点是第一层(level 1),以此类推
你可使用having
约束来得到特定的层级的节点
$result = Category::withDepth()->having('depth', '=', 1)->get();
注意 这在数据库严格模式下无效
全部的节点都是在内部严格组织的,默认状况下没有顺序,因此节点是随机展示的,这部影响展示,你能够按字母和其余的顺序对节点排序。
可是在一些状况下按层级展现是必要的,它对获取祖先和用于菜单顺序有用。
使用deaultOrder运用树的排序:$result = Category::defaultOrder()->get();
你也可使用倒序排序:$result = Category::reversed()->get();
让节点在父级内部上下移动来改变默认排序:
$bool = $node->down(); $bool = $node->up(); // 向下移动3个兄弟节点 $bool = $node->down(3);
操做返回根据操做的节点的位置是否改变的布尔值
不少约束条件能够被用到这些查询构造器上:
祖先约束
$result = Category::whereAncestorOf($node)->get(); $result = Category::whereAncestorOrSelf($id)->get();
$node
能够为模型的主键或者模型实例
后代约束
$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(); //结果集合中包含目标node自身 $result = Category::whereDescendantOrSelf($node)->get();
在获取了node的结果集合后,咱们就能够将它转化为树,例如:$tree = Category::get()->toTree();
这将在每一个node上添加parent 和 children 关系,且你可使用递归算法来渲染树:
$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
trait,且在模型层
检查节点是否为其余节点的子节点$bool = $node->isDescendantOf($parent);
检查是否为根节点$bool = $node->isRoot();
其余的检查
你能够检查树是否被破环$bool = Category::isBroken();
获取错误统计:$data = Category::countErrors();
它将返回含有一下键的数组
从v3.1日后支持修复树,经过parent_id字段的继承信息,给每一个node设置合适的lft 和 rgt值Node::fixTree();
假设你有个Memu模型和MenuItems.他们之间是one-to-many 关系。MenuItems有menu_id属性并实现nested sets模型。显然你想基于menu_id属性来单独处理每一个树,为了实现这样的功能,咱们须要指定这个menu_id属性为scope属性。
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();
但使用model实例查询node,scope自动基于设置的限制做用域属性来删选node。例如:
$node = MenuItem::findOrFail($id); $node->siblings()->withDepth()->get(); // OK
使用实例来获取删选的查询:$node->newScopedQuery();
注意,当经过主键获取模型时不须要使用scope
$node = MenuItem::findOrFail($id); // OK $node = MenuItem::scoped([ 'menu_id' => 5 ])->findOrFail(); // OK, 可是多余