laravel-nestedset icon indicating copy to clipboard operation
laravel-nestedset copied to clipboard

Wrong nodes being deleted

Open tuurbo opened this issue 8 years ago • 4 comments

When i delete trashed items, it is deleting some items that aren't trashed and that aren't descendants of other trashed items.

(i ran Folder::fixTree(); first and it returned zero)

Folder::onlyTrashed()->get()->each(function($folder) {
    $folder->forceDelete();
});

If i comment out lines 632 - 641 from https://github.com/lazychaser/laravel-nestedset/blob/v4/src/NodeTrait.php#L632-L641 It doesnt delete the wrong folders.

tuurbo avatar Jun 15 '17 20:06 tuurbo

If i comment out forceDelete() and get the descendants of the folders that would be deleted, I don't see the folders that are being wrongly deleted listed.

$data = [];
Folder::onlyTrashed()->get()->each(function($folder) use (&$data) {
    // $folder->forceDelete();
    $data[] = Folder::withTrashed()->descendantsAndSelf($folder->id);
});

return $data;

Hope this makes sense.

tuurbo avatar Jun 15 '17 21:06 tuurbo

Any ideas @lazychaser ?

tuurbo avatar Jun 22 '17 20:06 tuurbo

This may happen because deleting a node deletes it descendants, and you're selecting all trashed nodes, so there maybe a situation when you're trying to delete a node twice.

Try deleting & selecting nodes one by one.

  1. Select one trashed node
  2. Delete it
  3. Select next one

lazychaser avatar Sep 25 '17 07:09 lazychaser

This can be solved using this code, making sure to always have the actual database record inside the loop. If removing the $item directly, the _lft and _rgt may have been changed by previous forceDelete(), causing deletion of records that are not marked for deletion.

Folder::onlyTrashed()->each(function ($item)) {
    $itemWithNewData = Folder::withTrashed()->whereId($item->id)->first();
    $itemWithNewData->forceDelete();
});

@lazychaser Maybe a good one to update the documentation about this behavior?

dejury avatar Aug 31 '22 11:08 dejury