PHPackages                             medicivn/eloquent-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. medicivn/eloquent-nested-set

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

medicivn/eloquent-nested-set
============================

v1.0.10(3y ago)05.2kMITPHPPHP ^8.1

Since Jul 26Pushed 3y ago2 watchersCompare

[ Source](https://github.com/MediciVN/eloquent-nested-set)[ Packagist](https://packagist.org/packages/medicivn/eloquent-nested-set)[ RSS](/packages/medicivn-eloquent-nested-set/feed)WikiDiscussions 1.x Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (21)Used By (0)

EloquentNestedSet
=================

[](#eloquentnestedset)

Tự động cập nhật lại cây khi tạo mới, cập nhật và xóa một node.

Cách sử dụng:

- Đầu tiên, một Root node với `parent_id=0, left=1, right=2, depth=0` cần phải được khởi tạo ở table của bạn
- Thêm `use NestedSetModel;` vào trong Model tương ứng

```
use MediciVN\EloquentNestedSet\NestedSetModel;

class Category extends Model
{
    use NestedSetModel;

    /**
     * ID của Root node
     *
     * Mặc định: 1
     */
    const ROOT_ID = 99999;

    /**
     * Tên trường lưu vị trí bên trái của một node
     *
     * Mặc định: 'lft'
     *
     * Chú ý: kiểu dữ liệu trong Database cần cho phép lưu cả giá trị âm
     */
    const LEFT = 'lft';

    /**
     * Tên trường lưu vị trí bên phải của một node
     *
     * Mặc định: 'rgt'
     *
     * Chú ý: kiểu dữ liệu trong Database cần cho phép lưu cả giá trị âm
     */
    const RIGHT = 'rgt';

    /**
     * Tên trường lưu ID của node cha
     *
     * Mặc định: 'parent_id'
     */
    const PARENT_ID = 'parent_id';

    /**
     * Tên trường lưu giá trị độ sâu - cấp độ của một node
     *
     * Mặc định: 'depth'
     *
     * Giá trị depth của một node không ảnh hưởng đến việc tính toán left và rigth.
     * Bạn có thể khởi tạo root node với depth=0, hoặc bất cứ giá trị nào bạn muốn.
     */
    const DEPTH = 'depth';

    /**
     * Bạn có thể triển khai việc cập nhật lại vị trí các nodes với queue nếu lo ngại vấn đề về performance
     * Queue connection phải được khai báo trong `config/queue.php`.
     *
     * Mặc định: null
     */
    const QUEUE_CONNECTION = 'sqs';

    /**
     * Mặc định: null
     */
    const QUEUE = 'your_queue';

    /**
     * Mặc định: true
     */
    const QUEUE_AFTER_COMMIT = true;
```

Tính năng
---------

[](#tính-năng)

- `getTree`: lấy tất cả nodes và trả về dưới dạng `nested array`

    ```
        Category::getTree();
    ```
- `getFlatTree`: lấy tất cả nodes và trả về dưới dạng `flatten array`, các nodes con sẽ được sắp xếp ngay sau nút cha

    ```
        Category::getFlatTree();
    ```
- `getLeafNodes`: lấy tất cả các nodes lá - các node không có con cháu

    ```
        Category::getLeafNodes();
    ```
- `getAncestors`: lấy tất cả các nodes cha - ông (`ancestor`) của node hiện tại

    ```
        $node = Category::find(123);
        $node->getAncestors();
    ```
- `getAncestorsTree`: lấy tất cả các nodes cha - ông (`ancestor`) của node hiện tại và trả về dưới dạng `nested array`

    ```
        $node = Category::find(123);
        $node->getAncestorsTree();
    ```
- `getDescendants`: lấy tất cả các nodes con cháu (`descendant`) của node hiện tại

    ```
        $node = Category::find(123);
        $node->getDescendants();
    ```
- `getDescendantsTree`: lấy tất cả các nodes con cháu (`descendant`) của node hiện tại và trả về dưới dạng `nested array`

    ```
        $node = Category::find(123);
        $node->getDescendantsTree();
    ```
- `parent`: lấy node cha của node hiện tại

    ```
        $node = Category::find(123);
        $node->parent();
    ```
- `children`: lấy tất cả nodes con của node hiện tại

    ```
        $node = Category::find(123);
        $node->children();
    ```
- `buildNestedTree`: build a nested tree base on `parent_id`

    ```
        $categories = Category::withoutGlobalScope('ignore_root')->get();
        $tree = Category::buildNestedTree($categories);
    ```
- `fixTree`: tính toán lại toàn bộ tree dựa trên parent\_id

    ```
        Category::fixTree();
    ```

Query scopes
------------

[](#query-scopes)

[Laravel Eloquent Query Scopes](https://laravel.com/docs/9.x/eloquent#query-scopes)

Root node sẽ dự động bị bỏ qua ở tất cả truy vấn bởi `ignore_root` global scope.

Để làm việc với root node, sử dụng `withoutGlobalScope('ignore_root')`.

Các query scope khác:

- `ancestors`
- `descendants`
- `flattenTree`
- `leafNodes`

Chú ý
-----

[](#chú-ý)

- Nếu bạn sử dụng `queue` bạn sẽ cần phải sử dụng thêm `SoftDelete`, bởi vì `queue` sẽ thất bại trong trường hợp 1 node bị xóa hoàn toàn,
- Nếu bạn muốn sử dụng SQS-FIFO, hay tham khảo [this package](https://github.com/shiftonelabs/laravel-sqs-fifo-queue#configuration).

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~10 days

Total

12

Last Release

1270d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/82cf8224a32b96dbba4b0454806058ad5a4a418580f9ada2949b0454ad8ffbd2?d=identicon)[medicivn](/maintainers/medicivn)

---

Top Contributors

[![MediciVN](https://avatars.githubusercontent.com/u/107663288?v=4)](https://github.com/MediciVN "MediciVN (13 commits)")[![linhnc-medici](https://avatars.githubusercontent.com/u/105692913?v=4)](https://github.com/linhnc-medici "linhnc-medici (11 commits)")[![duyngha](https://avatars.githubusercontent.com/u/8712540?v=4)](https://github.com/duyngha "duyngha (3 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[laravel/scout

Laravel Scout provides a driver based solution to searching your Eloquent models.

1.7k49.4M479](/packages/laravel-scout)[silber/bouncer

Eloquent roles and abilities.

3.6k4.4M25](/packages/silber-bouncer)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.1M11](/packages/bavix-laravel-wallet)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)

PHPackages © 2026

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