diff --git a/src/Database/Model.php b/src/Database/Model.php index 16d902a6..a7bee33e 100644 --- a/src/Database/Model.php +++ b/src/Database/Model.php @@ -102,6 +102,28 @@ public function beforeUpdate() $this->updated_at = date('Y-m-d H:i:s'); } + /** + * Make a cascade softdelete. + * + * @return void + */ + public function cascadeSoftDelete(): void + { + foreach ($this->getDependentRelationships() as $relation => $data) { + $relationData = $this->{'get'.$relation}(); + + if ($data['type'] === Relation::HAS_ONE) { + if (isset($relationData)) { + $relationData->softDelete(); + } + } elseif ($data['type'] === Relation::HAS_MANY && isset($relationData[0])) { + foreach ($relationData as $singleData) { + $singleData->softDelete(); + } + } + } + } + /** * Soft Delete. * diff --git a/tests/integration/Database/ModelTest.php b/tests/integration/Database/ModelTest.php index a1109b31..251e8570 100644 --- a/tests/integration/Database/ModelTest.php +++ b/tests/integration/Database/ModelTest.php @@ -3,6 +3,7 @@ namespace Baka\Test\Integration\Database; use Baka\Test\Support\Models\LeadsNormal as Leads; +use Baka\Test\Support\Models\Users; use PhalconUnitTestCase; class ModelTest extends PhalconUnitTestCase @@ -110,4 +111,12 @@ public function testUpdateOrCreate() $this->assertTrue($lead->email == $email); $this->assertTrue(get_class($lead) == Leads::class); } + + public function testCascadeSoftDelete() + { + $user = Users::findFirst(); + $user->cascadeSoftDelete(); + + $this->assertEmpty($user->getSubscriptions()); + } }