laravel-nestedset
laravel-nestedset copied to clipboard
How to fix the tree after adding nesting set through a migration?
I need to add the nested set columns to an existing table. Adding the nested set columns with a migration like below works as intended, but the tree is in a faulty state after that. parent_id is null, which is fine, as a hierarchy cannot be known at this point. But _lft and _rgt is all 0, so all subsequent nested set functions don't work.
Schema::table('units', function (Blueprint $table) {
$table->nestedSet();
});
My first guess was to fix the tree using Unit::fixTree(). But this didn't do the trick. Also Unit::countErrors(); shows zero errors.
Expected behavior:
There should be some way to get the tree fixed. This means, that _lft and _rgt values have working values in some kind of order and the values should take into consideration an optional scope.
Getting the nested set fixed, after a migration should either be done by executing the migration using $table->nestedSet(); or by calling Unit::fixTree() or similar.
My additional workaround migration code using id as source value:
Without scoping:
\App\Unit::each(function (\App\Unit $unit) {
$unit->setLft($unit->id * 2 - 1);
$unit->setRgt($unit->id * 2);
$unit->save();
});
With scoping:
\App\Unit::each(function (\App\Unit $unit) {
$lowest = $unit->project->units->sortBy('id')->first()->id;
$unit->setLft(($unit->id - $lowest + 1) * 2 - 1);
$unit->setRgt(($unit->id - $lowest + 1) * 2);
$unit->save();
});