laravel-nestedset is a larvel4-5 plug-in package for relational database tree traversal. This article mainly shares laravel-nestedset multi-level infinite classification with you, hoping to help everyone.
Directory:
Nested Sets Model Introduction
Installation Requirements
Install
Get started
Migrate files
Insert node
Get node
Delete node
Consistency check and repair
Scope
Nested Set Model is a clever way to implement an ordered tree. , it is fast and does not require recursive queries. For example, no matter how many levels the tree has, you can use only one query to get all the descendants under a certain node. The disadvantage is that its insertion, movement, and deletion require the execution of complex SQL statements, but It’s all taken care of within this plugin!
See Wikipedia for more details! Nested set model and its Chinese translation! Nested collection model
PHP>=5.4
composer.json file:
"kalnoy/nestedset": "^4.3",
composer install to install it.
composer require kalnoy/nestedset
columns method of the
NestedSet class to add a field with a default name:
... 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, the source code is as follows:
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\NodeTraittrait to implement 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 field information, you need to add the following two columns of fields to your blueprint file:
$table->unsignedInteger('_lft'); $table->unsignedInteger('_rgt');
_lft and
_rgt fields:
MyModel::fixTree();
Attention!
For version v4.2.0, transaction is not automatically enabled. In addition, the structured operation of node requires manual save on the model, but some methods will implicitly execute save and return the Boolean result after the operation.Create Node
When you simply create a node, it is added to the end of the tree.Category::create($attributes); // 自动save为一个根节点(root)
$node = new Category($attributes); $node->save(); // save为一个根节点(root)
// #1 隐性 save $node->saveAsRoot(); // #2 显性 save $node->makeRoot()->save();
$parent
The methods for adding existing nodes to the end of the parent node include:
// #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);
$neighbor
of the specified node
$neighbor
$node can be a newly created node or an existing node. Exists, if
$node is an existing node, it will be moved to a new location adjacent to
$neighbor, and its parent will be changed if necessary.
# 显性save $node->afterNode($neighbor)->save(); $node->beforeNode($neighbor)->save(); # 隐性 save $node->insertAfterNode($neighbor); $node->insertBeforeNode($neighbor);
Build the array as a tree
But when using the children key, if any , will create more nodes recursively.
$node = Category::create([ 'name' => 'Foo', 'children' => [ [ 'name' => 'Bar', 'children' => [ [ 'name' => 'Baz' ], ], ], ], ]);
Now
$node->children contains a set of nodes that have been created. Reconstruct an array into a tree
$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);
操作返回根据操作的节点的位置是否改变的布尔值
很多约束条件可以被用到这些查询构造器上:
whereIsRoot() 仅获取根节点;
whereIsAfter($id) 获取特定id的节点后面的所有节点(不仅是兄弟节点)。
whereIsBefore($id) 获取特定id的节点前面的所有节点(不仅是兄弟节点)。
祖先约束
$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();
其他的检查
$node->isChildOf($other);
$node->isAncestorOf($other);
$node->isSiblingOf($other);
$node->isLeaf()
你可以检查树是否被破环$bool = Category::isBroken();
获取错误统计:$data = Category::countErrors();
它将返回含有一下键的数组
oddness -- lft 和 rgt 值错误的节点的数量
duplicates -- lft 或者 rgt 值重复的节点的数量
wrong_parent -- left 和 rgt 值 与parent_id 不对应的造成无效parent_id 的节点的数量
missing_parent -- 含有parent_id对应的父节点不存在的节点的数量
从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, 但是多余
相关推荐:
The above is the detailed content of Detailed explanation of laravel-nestedset multi-level infinite classification. For more information, please follow other related articles on the PHP Chinese website!