maso / treeify
Laravel 包允许您将模型扁平集合转换为层次树结构,简化父子关系管理。
v1.0.0
2024-09-02 17:04 UTC
Requires
- php: 7.4|^8.0
- illuminate/collections: ^8|^9|^10|^11
README
Treeify 包允许您轻松地将 Laravel 模型的扁平集合基于自父子关系转换为层次树结构。
安装
您可以通过 composer 安装此包。
composer require maso/treeify
使用方法
要使用 Treeify 包,只需将 HasTree 特性应用到您的 Eloquent 模型上,并使用 scopeTreeify 方法生成层次树结构。
use Maso\Treeify\Traits\HasTree; class Category extends Model { use HasTree; /** * The name of the field that identifies the parent ID. * * This field is optional. If not specified, the default field name 'parent_id' will be used * */ protected $parentFieldName = 'parent_id'; }
假设您数据库中存在以下分类
生成所有分类的完整树
$tree = Category::treeify();
预期输出
[ { "id": 1, "name": "Electronics", "children": [ { "id": 2, "name": "Laptops", "children": [ { "id": 5, "name": "Gaming Laptops" } ] }, { "id": 3, "name": "Desktops" }, { "id": 4, "name": "Smartphones" } ] } ]
从特定分类开始生成树
$category = Category::find(2); $categoryTree = $category->treeify();
预期输出
[ { "id": 2, "name": "Laptops", "children": [ { "id": 5, "name": "Gaming Laptops" } ] } ]
生成包含所有子父类的树
$tree = Category::treeify(false);
预期输出
此方法包括所有分类的层次结构,包括子父类。
[ { "id": 1, "name": "Electronics", "children": [ { "id": 2, "name": "Laptops", "children": [ { "id": 5, "name": "Gaming Laptops" } ] }, { "id": 3, "name": "Desktops" }, { "id": 4, "name": "Smartphones" } ] }, { "id": 2, "name": "Laptops", "children": [ { "id": 5, "name": "Gaming Laptops" } ] }, { "id": 3, "name": "Desktops" }, { "id": 4, "name": "Smartphones" } ]
更新日志
有关最近更改、更新或添加的信息,请参阅 更新日志。
安全
如果您发现任何安全相关的问题,请首先通过电子邮件发送至 majdsoubh53@gmail.com,如果我们不能在短时间内修复它,请打开一个新问题,描述您的问题。