PHPackages                             rundiz/nested-set - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. rundiz/nested-set

ActiveLibrary[Database &amp; ORM](/categories/database)

rundiz/nested-set
=================

class library for CRUD the nested set data such as category tree.

1.0.2(5y ago)343.1k11MITPHPPHP &gt;=7.0.0

Since Aug 27Pushed 5mo ago4 watchersCompare

[ Source](https://github.com/Rundiz/nested-set)[ Packagist](https://packagist.org/packages/rundiz/nested-set)[ RSS](/packages/rundiz-nested-set/feed)WikiDiscussions version1 Synced 2mo ago

READMEChangelog (3)DependenciesVersions (6)Used By (0)

NestedSet
=========

[](#nestedset)

The PHP nested set model for create/read/update/delete the tree data structure (hierarchy).

[![Latest Stable Version](https://camo.githubusercontent.com/e9362e22e44a7b1b4bffaf356d79af653bfb659339eb573ff47da91a38a696ac/68747470733a2f2f706f7365722e707567782e6f72672f72756e64697a2f6e65737465642d7365742f762f737461626c65)](https://packagist.org/packages/rundiz/nested-set)[![License](https://camo.githubusercontent.com/4bdb4bef52bccd76e7824617b4c44cba2923b29ad89d3f638ac1b73788281785/68747470733a2f2f706f7365722e707567782e6f72672f72756e64697a2f6e65737465642d7365742f6c6963656e7365)](https://packagist.org/packages/rundiz/nested-set)[![Total Downloads](https://camo.githubusercontent.com/7289a576c37a417757bd0c914f9ae79652f26c16d9dfbde67e9fa9a9dcc20ff4/68747470733a2f2f706f7365722e707567782e6f72672f72756e64697a2f6e65737465642d7365742f646f776e6c6f616473)](https://packagist.org/packages/rundiz/nested-set)

[![Nested Set](tests/via-http/nested-set-model.jpg "Nested Set")](tests/via-http/nested-set-model.jpg)

A class that help you to query complex data of nested set.

Tested up to PHP 8.5.

Example
-------

[](#example)

### Install

[](#install)

I recommend you to install this library via Composer and use Composer autoload for easily include the file. If you are not using Composer, you have to manually include the file by yourself.
Please make sure that the path to files are correct.

```
include_once '/path/to/Rundiz/src/NestedSet.php';
```

If you want to make sure or see how class is working please following the step below, otherwise skip this step.
Import **tests/common/test-database-structure.sql** file to the database.

---

### Connect to DB

[](#connect-to-db)

This class is using PDO class. Please connect to PDO and send the `\PDO` object to the class constructor.

```
$db['dsn'] = 'mysql:dbname=YOUR_DB_NAME;host=localhost;port=3306;charset=UTF8';
$db['username'] = 'admin';
$db['password'] = 'pass';
$db['options'] = [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION // throws PDOException.
];
$PDO = new \PDO($dbConfig['dsn'], $dbConfig['username'], $dbConfig['password'], $dbConfig['options']);
$NestedSet = new \Rundiz\NestedSet\NestedSet($PDO);
$NestedSet->tableName = 'test_taxonomy';// this should be your table name but you can use this for testing.
```

---

### Insert the data

[](#insert-the-data)

Before insert, you can get new position of that taxonomy level using `getNewPosition()` method.

```
$new_position = $NestedSet->getNewPosition(4);// result is 4.
```

Everytime you insert the data, you have to run `rebuild()` method to generate level, left, right data. The incorrect level, left, right data can cause incorrect listing.

```
$stmt = $PDO->prepare('INSERT INTO `test_taxonomy`(`parent_id`, `name`, `position`) VALUES (?, ?, ?)');
$stmt->execute([0, 'Root 4', 4]);
$NestedSet->rebuild();
```

---

### Update the data

[](#update-the-data)

To update the data, you don't need new position for this but you have to run `rebuild()` method every time.

```
$stmt = $PDO->prepare('UPDATE `test_taxonomy`SET `name` = ?, `position` = ? WHERE `id` = ?;
$stmt->execute(['Root 4 new name', 4, 21]);
$NestedSet->rebuild();
```

#### Check parent under children

[](#check-parent-under-children)

If you want to change the parent of selected item, you can check first that the new parent of selected item is under children of selected item or not.
You can use `isParentUnderMyChildren()` method to check this and `false` means correct parent (new parent is not children of editing item).
To continue on this please use the data in **demo-data.sql** file.

```
$editing_item_id = 9;
$new_parent_id = 7;
var_dump($NestedSet->isParentUnderMyChildren($editing_item_id, $new_parent_id));// false (CORRECT! the new parent is not child of this item)

$new_parent_id = 14;
var_dump($NestedSet->isParentUnderMyChildren($editing_item_id, $new_parent_id));// true (INCORRECT! the new parent is child of this item)
```

---

### Read the data

[](#read-the-data)

To read the selected item data with its children, you can use `getTaxonomyWithChildren()` method.

```
$options['filter_taxonomy_id'] = 3;// The selected item ID.
$list_txn = $NestedSet->getTaxonomyWithChildren($options);
unset($options);
print_r($list_txn);
```

To read the selected item data with its parent in a line until root item, you can use `getTaxonomyWithParents()` method.

```
$options['filter_taxonomy_id'] = 13;// The selected item ID.
$list_txn = $NestedSet->getTaxonomyWithParents($options);
unset($options);
print_r($list_txn);
```

### List the items

[](#list-the-items)

You can list the items by use `listTaxonomy()` method for nested array data or use `listTaxonomyFlatten()` for flatten data.

```
$options = [];
$options['unlimited'] = true;
$list_txn = $NestedSet->listTaxonomy($options);
unset($options);
// The variable $list_txn is array and have 2 keys (total, items).
```

Both methods parameters are same.

---

### Delete an item

[](#delete-an-item)

You can choose how to delete an item.

1. Delete selected item and ALL of its children.
2. Delete selected item and pull up its children to the current parent.

Every time you deleted, you have to run the `rebuild()` method to correct level, left, right data.

Delete selected item and ALL of its children.

```
$NestedSet->deleteWithChildren(16);
$NestedSet->rebuild();
```

Delete selected item and pull up its children to the current parent.

```
$NestedSet->deletePullUpChildren(9);
$NestedSet->rebuild();
```

For more example including complex conditions which is new feature since v 1.x, please take a look in **tests/phpunit** folder or the API document in **.wiki/apidoc** folder.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance49

Moderate activity, may be stable

Popularity29

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~549 days

Total

4

Last Release

1899d ago

Major Versions

v0.1 → 1.02020-09-18

PHP version history (2 changes)v0.1PHP &gt;=5.3.0

1.0PHP &gt;=7.0.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1568262?v=4)[vee w,](/maintainers/ve3)[@ve3](https://github.com/ve3)

---

Top Contributors

[![ve3](https://avatars.githubusercontent.com/u/1568262?v=4)](https://github.com/ve3 "ve3 (30 commits)")

---

Tags

databasehierarchynested-setnested-structurestaxonomycategorieshierarchynested-setcategorycategory treenested treesub categorysub categoriesnested modeltree model

### Embed Badge

![Health badge](/badges/rundiz-nested-set/health.svg)

```
[![Health](https://phpackages.com/badges/rundiz-nested-set/health.svg)](https://phpackages.com/packages/rundiz-nested-set)
```

###  Alternatives

[kalnoy/nestedset

Nested Set Model for Laravel 5.7 and up

3.8k13.3M213](/packages/kalnoy-nestedset)[franzose/closure-table

Adjacency List’ed Closure Table database design pattern implementation for Laravel

4641.1M3](/packages/franzose-closure-table)[baum/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

2.3k1.6M55](/packages/baum-baum)[rinvex/laravel-categories

Rinvex Categories is a polymorphic Laravel package, for category management. You can categorize any eloquent model with ease, and utilize the power of Nested Sets, and the awesomeness of Sluggable, and Translatable models out of the box.

470161.6k3](/packages/rinvex-laravel-categories)[baril/bonsai

An implementation of the Closure Tables pattern for Eloquent.

3593.5k](/packages/baril-bonsai)[gazsp/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

129341.3k5](/packages/gazsp-baum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
