PHP code example of on1kel / hyperf-nestedset

1. Go to this page and download the library: Download on1kel/hyperf-nestedset library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

on1kel / hyperf-nestedset example snippets




declare(strict_types=1);

namespace App\Model;

use Hyperf\Database\Model\Model;
use On1kel\NestedSet\UseTree;

class Category extends Model
{
    use UseTree;

    protected ?string $table = 'categories';

    protected array $fillable = ['name', 'parent_id'];
}



use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;
use On1kel\NestedSet\Database\Migrate;
use App\Model\Category;

class CreateCategoriesTable extends Migration
{
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            
            // Добавить колонки nested set из модели
            Migrate::columnsFromModel($table, Category::class);
            
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
}

// Для модели с одним деревом
$root = new Category(['name' => 'Корень']);
$root->saveAsRoot();

// Или используя makeRoot()
$root = new Category(['name' => 'Корень']);
$root->makeRoot()->save();

// Добавить в конец (как последний дочерний)
$child = new Category(['name' => 'Дочерний']);
$child->appendTo($parent)->save();

// Добавить в начало (как первый дочерний)
$child = new Category(['name' => 'Дочерний']);
$child->prependTo($parent)->save();

// Вставить перед узлом
$sibling = new Category(['name' => 'Сосед']);
$sibling->insertBefore($existingNode)->save();

// Вставить после узла
$sibling = new Category(['name' => 'Сосед']);
$sibling->insertAfter($existingNode)->save();

// Переместить узел к другому родителю
$node->appendTo($newParent)->save();

// Переместить узел перед соседом
$node->insertBefore($sibling)->save();

// Переместить узел после соседа
$node->insertAfter($sibling)->save();

// Переместить вверх среди соседей
$node->up();

// Переместить вниз среди соседей
$node->down();

$root = Category::root()->first();
// или
$root = $node->getRoot();

$parent = $node->parent;

$children = $node->children;

$ancestors = $node->ancestors;
// или через query builder
$ancestors = $node->parents();

$descendants = $node->descendants;
// или через query builder
$descendants = $node->newQuery()->descendantsQuery()->get();

$siblings = $node->siblings()->get();
$siblingsAndSelf = $node->siblingsAndSelf()->get();

$leaves = $node->leaves()->get();

$tree = Category::defaultOrder()->get()->toTree();

$node->isRoot();    // Это корневой узел?
$node->isLeaf();    // Это лист (без детей)?
$node->isChildOf($otherNode);  // Это дочерний узел другого?

// Удалить узел (дети будут перемещены к родителю)
$node->delete();

// Удалить узел со всеми потомками
$node->deleteWithChildren();



namespace App\Model;

use Hyperf\Database\Model\Model;
use On1kel\NestedSet\UseTree;
use On1kel\NestedSet\Config\Builder;

class Category extends Model
{
    use UseTree;

    protected static function buildTree(): Builder
    {
        return Builder::defaultMulti();
    }
}

// Создать корни для разных деревьев
$tree1Root = new Category(['name' => 'Корень дерева 1']);
$tree1Root->setTree(1)->saveAsRoot();

$tree2Root = new Category(['name' => 'Корень дерева 2']);
$tree2Root->setTree(2)->saveAsRoot();

// Запрос по дереву
$tree1Nodes = Category::byTree(1)->get();

// Получить только корневые узлы
Category::root()->get();

// Получить узлы по дереву (только multi-tree)
Category::byTree($treeId)->get();

// Получить узлы по уровню
Category::byLevel(2)->get();

// Получить узлы до определенного уровня
Category::toLevel(3)->get();

// Сортировка по умолчанию (по левому атрибуту)
Category::defaultOrder()->get();