public function rebuild()
    {
        $i = 0;
        $skip = [];
        while (0 != $this->filter(['lft__isnull' => true])->count()) {
            ++$i;
            $fixed = 0;
            echo 'Iteration: '.$i.PHP_EOL;

            $clone = clone $this;
            /** @var TreeModel[] $models */
            $models = $clone
                ->exclude(['pk__in' => $skip])
                ->filter(['lft__isnull' => true])
                ->order(['parent_id'])
                ->all();

            foreach ($models as $model) {
                $model->lft = $model->rgt = $model->level = $model->root = null;
                if ($model->saveRebuild()) {
                    $skip[] = $model->pk;
                    ++$fixed;
                }
                echo '.';
            }
            echo PHP_EOL;
            echo 'Fixed: '.$fixed.PHP_EOL;
        }
    }
public function rebuild()
    {
        $i = 0;
        $skip = [];
        while (0 != $this->filter(['lft__isnull' => true])->count()) {
            ++$i;
            $fixed = 0;
            echo 'Iteration: '.$i.PHP_EOL;

            $clone = clone $this;
            /** @var TreeModel[] $models */
            $models = $clone
                ->exclude(['pk__in' => $skip])
                ->filter(['lft__isnull' => true])
                ->order(['parent_id'])
                ->all();

            foreach ($models as $model) {
                $model->lft = $model->rgt = $model->level = $model->root = null;
                if ($model->saveRebuild()) {
                    $skip[] = $model->pk;
                    ++$fixed;
                }
                echo '.';
            }
            echo PHP_EOL;
            echo 'Fixed: '.$fixed.PHP_EOL;
        }
    }
public function rebuild ( ) { $ i = 0 ; $ skip = [ ] ; while ( 0 != $ this -> filter ( [ 'lft__isnull' => true ] ) -> count ( ) ) { ++ $ i ; $ fixed = 0 ; echo 'Iteration: ' . $ i . PHP_EOL ; $ clone = clone $ this ; /** @var TreeModel[] $models */ $ models = $ clone -> exclude ( [ 'pk__in' => $ skip ] ) -> filter ( [ 'lft__isnull' => true ] ) -> order ( [ 'parent_id' ] ) -> all ( ) ; foreach ( $ models as $ model ) { $ model -> lft = $ model -> rgt = $ model -> level = $ model -> root = null ; if ( $ model -> saveRebuild ( ) ) { $ skip [ ] = $ model -> pk ; ++ $ fixed ; } echo '.' ; } echo PHP_EOL ; echo 'Fixed: ' . $ fixed . PHP_EOL ; } }
Completely rebuild broken tree
Completely rebuild broken tree