Skip to content

Commit

Permalink
Merge 4fe9a96 into a373495
Browse files Browse the repository at this point in the history
  • Loading branch information
ADmad committed Feb 13, 2020
2 parents a373495 + 4fe9a96 commit 149cf90
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/ORM/Behavior/CounterCacheBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,11 +219,24 @@ protected function _processAssociation(
array $settings
): void {
$foreignKeys = (array)$assoc->getForeignKey();
$primaryKeys = (array)$assoc->getBindingKey();
$countConditions = $entity->extract($foreignKeys);
$allNulls = true;
foreach ($countConditions as $field => $value) {
if ($value === null) {
$countConditions[$field . ' IS'] = $value;
unset($countConditions[$field]);
} else {
$allNulls = false;
}
}
if ($allNulls) {
return;
}

$primaryKeys = (array)$assoc->getBindingKey();
$updateConditions = array_combine($primaryKeys, $countConditions);
$countOriginalConditions = $entity->extractOriginalChanged($foreignKeys);

$countOriginalConditions = $entity->extractOriginalChanged($foreignKeys);
if ($countOriginalConditions !== []) {
$updateOriginalConditions = array_combine($primaryKeys, $countOriginalConditions);
}
Expand Down
21 changes: 21 additions & 0 deletions tests/TestCase/ORM/Behavior/CounterCacheBehaviorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,27 @@ public function testAddScope()
$this->assertEquals(2, $after->get('posts_published'));
}

/**
* @return void
*/
public function testSaveWithNullForeignKey()
{
$this->comment->belongsTo('Users');

$this->comment->addBehavior('CounterCache', [
'Users' => [
'comment_count',
],
]);

$entity = new Entity([
'title' => 'Orphan comment',
'user_id' => null,
]);
$this->comment->save($entity);
$this->assertTrue(true);
}

/**
* Testing simple counter caching when deleting a record
*
Expand Down

0 comments on commit 149cf90

Please sign in to comment.