Skip to content

Commit

Permalink
fix: deletion of records
Browse files Browse the repository at this point in the history
  • Loading branch information
saade committed Feb 6, 2024
1 parent 5a4cca9 commit 76fb9e7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/Forms/Components/AdjacencyList.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ protected function setUp(): void
$item[$orderColumn] = array_search($key, array_keys($items));
}

// TODO: add ignore columns method
$data = Arr::except($item, [$recordKeyName, $childrenKey, 'path', 'depth']);

// Update or create record
Expand Down
16 changes: 15 additions & 1 deletion src/Forms/Components/NestedSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Saade\FilamentAdjacencyList\Forms\Components;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Arr;
Expand Down Expand Up @@ -29,10 +30,11 @@ protected function setUp(): void
}

$cachedExistingRecords = $component->getCachedExistingRecords();
$existingItemsIds = [];

$data = collect($state)
->map(
$cb = function ($item, $key, $children = []) use (&$cb, $component, $state, $cachedExistingRecords) {
$cb = function (array $item, string $key, array $children = []) use (&$cb, $component, $state, $cachedExistingRecords, &$existingItemsIds): array {
$relationship = $component->getRelationship();

$childrenKey = $component->getChildrenKey();
Expand All @@ -44,6 +46,7 @@ protected function setUp(): void
$item[$orderColumn] = array_search($key, array_keys($children ?: $state));
}

// TODO: add ignore columns method
$data = Arr::except($item, [$childrenKey, 'parent_id', '_lft', '_rgt', 'created_at', 'updated_at', 'deleted_at']);

// Update or create record
Expand All @@ -60,13 +63,24 @@ protected function setUp(): void
->toArray();
}

// Update cached existing records
$existingItemsIds[] = $data[$recordKeyName];

return $data;
}
)
->toArray();

$component->getRelatedModel()::rebuildTree($data);

// Delete removed records
$cachedExistingRecords
->filter(fn (Model $record) => ! in_array($record->getKey(), $existingItemsIds))
->each(function (Model $record) use ($cachedExistingRecords) {
$record->delete();
$cachedExistingRecords->forget("record-{$record->getKey()}");
});

$component->fillFromRelationship(cached: false);
});

Expand Down

0 comments on commit 76fb9e7

Please sign in to comment.