ibelousov/advanced-nested-set

1.0.0 2023-03-15 08:43 UTC

This package is auto-updated.

Last update: 2024-09-15 12:13:27 UTC


README

注意

目前仅支持 POSTGRESQL、MYSQL 和 SQLITE 数据库

概览

Advanced nested set 是一个 Laravel 包,可用于处理嵌套树集,如下所示

Category::first()->descendants; // print all nested categories of category

或如下所示

Category::whereHas('parents', function($query) {
    $query->where('name', 'vegetables');
});

安装

使用包管理器 composer 安装它

composer require ibelousov/advanced-nested-set

用法

设置

因此,您有一个 Category 模型并希望向其中添加嵌套集。为此,您可以

1) 创建并执行迁移

    public function up()
    {
        Schema::table('categories', function (Blueprint $table) {
             $table->advancedNestedSet(); // create columns lft,rgt,depth,parent_id,deleted_at
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('categories', function (Blueprint $table) {
             $table->dropAdvancedNestedSet(); // delete columns lft,rgt,depth,parent_id,deleted_at
        });
    }

2) 向模型添加 AdvancedNestedSet

use \Ibelousov\AdvancedNestedSet\AdvancedNestedSet;

class Category extends Model
{
    use AdvancedNestedSet;

    protected $fillable = [/*...Your columns..*/ 'lft','rgt','parent_id','depth','distance'];
}

3) 修复嵌套集(如果 Category 中有记录)

    php artisan advanced-nested-set:fix categories

4) 如果已经使用了 "ADVANCED_NESTED_SET_LOCK_" 前缀用于在 CRUD 上进行阻塞,但不适合您的需求

添加到 .env

ADVANCED_NESTED_LOCK_NAME="NEW_LOCK_NAME"

5) 微调阻塞的时间

添加到 .env

ADVANCED_NESTED_LOCK_WAIT=100 # Seconds waiting for atomic blocking(DEFAULT: 30)
ADVANCED_NESTED_LOCK_DELAY=9999999 # Microseconds waiting after blocking(DEFAULT: 10000)

创建/更新/删除节点

  • 创建节点
$node = Category::create([...]); // Root node
  • 在父节点内创建节点:
Category::create(['parent_id' => $node->id]); // Child of Root node
  • 将节点从父节点移动到根节点
$category->update(['parent_id' => null]);
  • 将节点移动到另一个父节点
$category->update(['parent_id' => $parentId]);
  • 在父节点内部移动节点
$category->moveAfter($category2);

关系

// descendants of category
Category::first()->descendants;
// descendants of category and category itself
Category::first()->descendants_and_self;
// parents of category
Category::first()->parents;
// parents and self category of category
Category::first()->parents_and_self;
// parent of category
Category::first()->parent;
// children of category
Category::first()->children;

方法

// Is nested set correct
Category::isCorrect();
// Get errors
Category::errors();
// Convert to treeStructure
Category::get()->toTree();

// Convert to tree and than to array
Category::get()->toTree()->toArray();

控制台命令

修复表

要修复表中的嵌套集,可以使用

php artisan advanced-nested-set:fix tablename

您可以将此命令添加到计划任务中,以保持嵌套集处于正确状态

检查表

要检查表中的嵌套集,可以使用

php artisan advanced-nested-set:check tablename --verbose

重要

由于此包使用缓存,为了正确处理原子锁进程之间的处理,建议使用 redis/memcached 或其他内存数据库以获得速度和准确性