NestedTree Notes

Wiki:

https://en.wikipedia.org/wiki/Nested_set_model

Update nest_left and nest_right values of all nodes:

    public function refresh_nested_tree(){
        $root_id = 10;
        $index = 1;
        $arr = [];
        $root = CategoryM::find($root_id);
        $this->loop_children($root, $index, $arr);
        logg($arr);
    }

    private function loop_children($node, &$index, &$arr){
        $arr[] = [$node->id, $index];
        $node->nest_left = $index;

        $children = CategoryM::where('parent_id', $node->id)
            ->orderBy('sort_order')
            ->get();

        if($children == false || count($children) == 0){
            $index++;
            $node->nest_right = $index;
            $node->save();
            return;
        }

        foreach($children as $key => $child){
            $index++;
            $this->loop_children($child, $index, $arr);
        }

        $index++;
        $node->nest_right = $index;
        $node->save();
    }

Notes:

  • In October CMS, a category must have nest_left and nest_right values or it will cause serious error.