Skip to content

Commit

Permalink
Implementing CascadeCallbacks when using saveStrategy. optimized in _…
Browse files Browse the repository at this point in the history
…unlinkAssociated
  • Loading branch information
mylux committed Oct 4, 2015
1 parent 3bad846 commit e82e801
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
27 changes: 16 additions & 11 deletions src/ORM/Association/HasMany.php
Expand Up @@ -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);
Expand Down
5 changes: 3 additions & 2 deletions tests/TestCase/ORM/TableTest.php
Expand Up @@ -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]));
}

Expand Down

0 comments on commit e82e801

Please sign in to comment.