maso/treeify
最新稳定版本:v1.0.0
Composer 安装命令:
composer require maso/treeify
包简介
Laravel package allows you to convert flat collections of models into hierarchical tree structures, simplifying parent-child relationships management.
关键字:
README 文档
README
The Treeify package allows you to easily convert flat collections of Laravel models into hierarchical tree structures based on self-parent-child relationships.
Installation
You can install the package via composer:
composer require maso/treeify
Usage
To use the Treeify package, simply apply the HasTree trait to your Eloquent models and utilize the scopeTreeify method to generate a hierarchical tree structure:
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'; }
Assuming you have the following categories in your database:
| id | name | parent_id |
|---|---|---|
| 1 | Electronics | NULL |
| 2 | Laptops | 1 |
| 3 | Desktops | 1 |
| 4 | Smartphones | 1 |
| 5 | Gaming Laptops | 2 |
Generating a Full Tree for All Categories
$tree = Category::treeify();
Expected Output
[
{
"id": 1,
"name": "Electronics",
"children": [
{
"id": 2,
"name": "Laptops",
"children": [
{
"id": 5,
"name": "Gaming Laptops"
}
]
},
{
"id": 3,
"name": "Desktops"
},
{
"id": 4,
"name": "Smartphones"
}
]
}
]
Generating a Tree Starting from a Specific Category
$category = Category::find(2); $categoryTree = $category->treeify();
Expected Output
[
{
"id": 2,
"name": "Laptops",
"children": [
{
"id": 5,
"name": "Gaming Laptops"
}
]
}
]
Generating Trees Including All Sub-Parents
$tree = Category::treeify(false);
Expected Output
This method includes all categories in the hierarchy, including sub-parents
[
{
"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"
}
]
Changelog
Please see the CHANGELOG for more information about what has changed or updated or added recently.
Security
If you discover any security related issues, please email them first to majdsoubh53@gmail.com, if we do not fix it within a short period of time please open a new issue describing your problem.
Credits
统计信息
- 总下载量: 25
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-09-02