laravel-nestedset是一个关系型数据库遍历树的larvel4-5的插件包,本文主要和大家分享laravel-nestedset多级无限分类,希望能帮助到大家。
目录:
nested sets model简介
安装要求
安装
开始使用
迁移文件
插入节点
获取节点
删除节点
一致性检查和修复
作用域
nested sets model简介nested set model 是一种实现有序树的高明的方法,它快速且不需要递归查询,例如不管树有多少层,你可以仅使用一条查询来获取某个节点下的所有的后代,缺点是它的插入、移动、删除需要执行复杂的sql语句,但是这些都在这个插件内处理了!
更多关于详见维基百科!nested set model 及它中文翻译!嵌套集合模型
安装要求php>=5.4
laravel>=4.1
v4.3版本以后支持laravel-5.5
v4版本支持laravel-5.2、5.3、5.4
v3版本支持laravel-5.1
v2版本支持laravel-4
强烈建议使用支持事物功能的数据引擎(像mysql的innodb)来防止可能的数据损坏。
安装在composer.json文件中加入下面代码:
kalnoy/nestedset: ^4.3,
运行composer install 来安装它。
或者直接在命令行输入
composer require kalnoy/nestedset
如需安装历史版本请点击更多版本
开始使用迁移文件你可以使用nestedset类的columns方法来添加有默认名字的字段:
...
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\nodetraittrait 来实现nested sets
use kalnoy\nestedset\nodetrait;
class foo extends model {
use nodetrait;
}
迁移其他地方已有的数据从其他的nested set 模型库迁移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具有以下功能,他们功能完全且被预加载:
node belongs to parent
node has many children
node has many ancestors
node has many descendants
假设我们有一个category模型;变量$node是该模型的一个实例是我们操作的node(节点)。它可以为一个新创建的node或者是从数据库中取出的node
插入节点(node)每次插入或者移动一个节点都要执行好几条数据库操作,所有强烈推荐使用transaction.
注意! 对于v4.2.0版本不是自动开启transaction的,另外node的结构化操作需要在模型上手动执行save,但是有些方法会隐性执行save并返回操作后的布尔类型的结果。
创建节点(node)当你简单的创建一个node,它会被添加到树的末端。
category::create($attributes); // 自动save为一个根节点(root)
或者
$node = new category($attributes);
$node->save(); // save为一个根节点(root)
在这里node被设置为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();
获取表的相关model假设每一个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深度(depth)如果你需要知道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();
这将破坏树结构
支持softdeletestrait,且在模型层
helper 方法检查节点是否为其他节点的子节点
$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();
作用域(scope)假设你有个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, 但是多余
相关推荐:
php实现多级分类筛选程序代码
php 查询多级分类的实例程序代码
smarty实现多级分类的方法_php技巧
以上就是laravel-nestedset多级无限分类详解的详细内容。