From e82e801846f77759cf57c1abb1afa4a9904e5a6b Mon Sep 17 00:00:00 2001 From: Luan Hospodarsky Date: Sat, 3 Oct 2015 21:17:11 -0300 Subject: [PATCH] Implementing CascadeCallbacks when using saveStrategy. optimized in _unlinkAssociated --- src/ORM/Association/HasMany.php | 27 ++++++++++++++++----------- tests/TestCase/ORM/TableTest.php | 5 +++-- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/ORM/Association/HasMany.php b/src/ORM/Association/HasMany.php index f21189ac372..166989ef6ec 100644 --- a/src/ORM/Association/HasMany.php +++ b/src/ORM/Association/HasMany.php @@ -195,21 +195,26 @@ protected function _unlinkAssociated(array $properties, EntityInterface $entity, $primaryKey = (array)$target->primaryKey(); $mustBeDependent = (!$this->_foreignKeyAcceptsNull($target, $properties) || $this->dependent()); $conditions = [ - 'AND' => [ - 'NOT' => [ - 'OR' => array_map( - function ($ent) use ($primaryKey) { - return $ent->extract($primaryKey); - }, - $remainingEntities - ) - ], - $properties - ] + 'NOT' => [ + 'OR' => array_map( + function ($ent) use ($primaryKey) { + return $ent->extract($primaryKey); + }, + $remainingEntities + ) + ], + $properties ]; if ($mustBeDependent) { + if ($this->_cascadeCallbacks) { + $query = $this->find('all')->where($conditions); + foreach ($query as $assoc) { + $target->delete($assoc); + } + } else { $target->deleteAll($conditions); + } } else { $updateFields = array_fill_keys(array_keys($properties), null); $target->updateAll($updateFields, $conditions); diff --git a/tests/TestCase/ORM/TableTest.php b/tests/TestCase/ORM/TableTest.php index b43e9e9cc16..c2ea9732447 100644 --- a/tests/TestCase/ORM/TableTest.php +++ b/tests/TestCase/ORM/TableTest.php @@ -1925,15 +1925,16 @@ public function testSaveReplaceSaveStrategyNotNullable() $article = $articles->save($article, ['associated' => ['Comments']]); $commentId = $article->comments[0]->id; + $sizeComments = count($article->comments); - $this->assertEquals(2, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); + $this->assertEquals($sizeComments, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); $this->assertTrue($articles->Comments->exists(['id' => $commentId])); unset($article->comments[0]); $article->dirty('comments', true); $article = $articles->save($article, ['associated' => ['Comments']]); - $this->assertEquals(1, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); + $this->assertEquals($sizeComments - 1, $articles->Comments->find('all')->where(['article_id' => $article->id])->count()); $this->assertFalse($articles->Comments->exists(['id' => $commentId])); }