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 */