Skip to content

Commit

Permalink
Merge pull request #74 from bakaphp/create-soft-delete-cascade
Browse files Browse the repository at this point in the history
Create soft delete cascade
  • Loading branch information
arfenis authored Jan 20, 2021
2 parents 76b9459 + cf51c15 commit 391fd18
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Database/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/integration/Database/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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());
}
}

0 comments on commit 391fd18

Please sign in to comment.