malith124 / materialized-path
Laravel 10 的物化路径特性
1.0.8
2024-09-13 15:20 UTC
Requires
- php: ^8.0
- illuminate/support: ^10.0
This package is auto-updated.
Last update: 2024-09-13 15:21:54 UTC
README
安装
- 将
langaner/materialized-path
添加到composer.json
文件中。
"langaner/materialized-path": "dev-master"
2)运行 composer update
以获取包的最新版本。
3)现在打开 app/config/app.php 文件,并将服务提供者添加到 providers 数组中。
Langaner\MaterializedPath\MaterializedPathServiceProvider::class,
4)将特性添加到需要树实现模型的类中
use \Langaner\MaterializedPath\MaterializedPathTrait;
迁移
表迁移示例 page_table
Schema::create('page_table', function(Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); // parent id $table->integer('parent_id')->unsigned()->nullable(); // depth path consisting of models id $table->string('path'); // depth path consisting of models alias $table->string('real_path')->unique(); // alias field $table->string('alias')->unique(); // order position $table->integer('position')->default(0)->index(); // depth level $table->integer('level')->default(0)->index(); $table->foreign('parent_id')->references('id')->on('page_table')->onDelete('cascade'); });
可用方法
// Make model is root with(new Page())->makeRoot(); // Make model first children by parent id with(new Page())->makeFirstChildOf($parentId); // Make model last children by parent id with(new Page())->makeLastChildOf($parentId); // Make previous sibling $page = Page::find(2); $page->makePreviousSiblingOf(Page::find(1)); // Make next sibling $page = Page::find(2); $page->makeNextSiblingOf(Page::find(1)); // Update model data $page = Page::find(1); $page->position = 2; with(new Page())->updateNode($page); // Get parent Page::find(1)->parent()->get(); // Get sibling Page::find(1)->sibling()->get(); // Get childrens by depth Page::find(1)->childrenByDepth()->get(); // Get parents by depth Page::find(1)->parentByDepth()->get(); // Descendant check Page::find(1)->isDescendantOf(Page::find(2)); // Ancestor check Page::find(1)->isAncestorOf(Page::find(2)); // Is leaf Page::find(1)->isLeaf(); // All leafs of model Page::allLeaf(); // All roots of model Page::allRoot(); // Get exploded path Page::find(1)->getExplodedPath(); // Build real path by entities with(new Page())->buildRealPath($ids); // Build model tree Page::find(1)->buildTree(); // Build model tree by parent id Page::find(1)->buildChidrenTree();
配置
发布资产 php artisan vendor:publish
此命令初始化配置文件,位于 app/config/packages/langaner/materialized-path/materialized_path.php。
如果需要在结果模型中翻译,将 with_translations
设置为 true
。此选项需要翻译包 https://github.com/dimsav/laravel-translatable