From 0707dcf47210e610857fc23efde56f11eda1449c Mon Sep 17 00:00:00 2001 From: Alwin Garside Date: Mon, 28 Oct 2024 10:54:41 +0100 Subject: [PATCH] feat: #145 ForceDelete functionality added --- src/SoftCascade.php | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/SoftCascade.php b/src/SoftCascade.php index c8534bc..8c1a933 100644 --- a/src/SoftCascade.php +++ b/src/SoftCascade.php @@ -193,7 +193,7 @@ protected function getMorphManyData($relation, $foreignKeyIds) } /** - * Execute delete, or restore. + * Execute delete or restore or forcedelete. * * @param Illuminate\Database\Eloquent\Relations\Relation $relation * @param string $foreignKey @@ -211,7 +211,13 @@ protected function execute($relation, $foreignKey, $foreignKeyIds, $affectedRows $relationModel = $relationModel->whereIn($foreignKey, $foreignKeyIds)->limit($affectedRows); $this->run($relationModel->get([$relationModel->getModel()->getKeyName()])); - $relationModel->{$this->direction}($this->directionData); + + // COMMIT : force delete when parent model "isForceDeleting = true" + if ($this->isForceDeleting($relation)) { + $relationModel->forceDelete(); + } else { + $relationModel->{$this->direction}($this->directionData); + } } } @@ -251,7 +257,12 @@ protected function validateRelation($model, $relation) protected function affectedRows($relation, $foreignKey, $foreignKeyIds) { $relationModel = $relation->getQuery()->getModel(); - $relationModel = $this->withTrashed($relationModel::query()); + $relationModel = new $relationModel(); + + // COMMIT : retreive relation trashed items when parent model "isForceDeleting = true" + if ($this->direction !== 'delete' || $this->isForceDeleting($relation)) { + $relationModel = $relationModel->withTrashed(); + } return $relationModel->whereIn($foreignKey, $foreignKeyIds)->count(); } @@ -291,4 +302,15 @@ protected function withTrashed(Builder $builder): Builder return $builder; } + + /** + * COMMIT + * Check if parent has a force delete enabled + * @return boolean + */ + protected function isForceDeleting($relation) + { + $parent = $relation->getParent(); + return property_exists($parent, 'forceDeleting') && $parent->isForceDeleting(); + } }