From cdf435af1cc1fea20079059312870533b1fbdecd Mon Sep 17 00:00:00 2001 From: Samuel Georges Date: Sun, 18 Feb 2024 13:59:09 +1100 Subject: [PATCH] Propagate multisite deletes --- src/Database/Traits/Multisite.php | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/Database/Traits/Multisite.php b/src/Database/Traits/Multisite.php index 3aa37cf3f..815702078 100644 --- a/src/Database/Traits/Multisite.php +++ b/src/Database/Traits/Multisite.php @@ -58,6 +58,8 @@ public function initializeMultisite() $this->bindEvent('model.saveComplete', [$this, 'multisiteSaveComplete']); + $this->bindEvent('model.afterDelete', [$this, 'multisiteAfterDelete']); + $this->defineMultisiteRelations(); } @@ -123,6 +125,24 @@ public function multisiteAfterCreate() ; } + /** + * multisiteAfterDelete + */ + public function multisiteAfterDelete() + { + if (!$this->isMultisiteSyncEnabled() || !$this->getMultisiteConfig('delete', true)) { + return; + } + + Site::withGlobalContext(function() { + foreach ($this->getMultisiteSyncSites() as $siteId) { + if (!$this->isModelUsingSameSite($siteId)) { + $this->deleteForSite($siteId); + } + } + }); + } + /** * defineMultisiteRelations will spin over every relation and apply propagation config */ @@ -376,6 +396,30 @@ protected function findOtherSiteModel($siteId = null) return $otherModel; } + /** + * deleteForSite runs the delete command on a model for another site, useful for cleaning + * up records for other sites when the parent is deleted. + */ + public function deleteForSite($siteId = null) + { + $otherModel = $this->findForSite($siteId); + if (!$otherModel) { + return; + } + + $useSoftDeletes = $this->isClassInstanceOf(\October\Contracts\Database\SoftDeleteInterface::class); + if ($useSoftDeletes && !$this->isSoftDelete()) { + static::withoutEvents(function() use ($otherModel) { + $otherModel->forceDelete(); + }); + return; + } + + static::withoutEvents(function() use ($otherModel) { + $otherModel->delete(); + }); + } + /** * isModelUsingSameSite */