diff --git a/src/ORM/Association/HasMany.php b/src/ORM/Association/HasMany.php index 04cf03458fc..78980d2bff2 100644 --- a/src/ORM/Association/HasMany.php +++ b/src/ORM/Association/HasMany.php @@ -306,7 +306,8 @@ public function unlink(EntityInterface $sourceEntity, array $targetEntities, $op $this->_unlink($foreignKey, $target, $conditions, $options); - if ($options['cleanProperty']) { + $result = $sourceEntity->get($property); + if ($options['cleanProperty'] && $result !== null) { $sourceEntity->set( $property, (new Collection($sourceEntity->get($property))) diff --git a/tests/TestCase/ORM/TableTest.php b/tests/TestCase/ORM/TableTest.php index bd981a7535b..5705367f937 100644 --- a/tests/TestCase/ORM/TableTest.php +++ b/tests/TestCase/ORM/TableTest.php @@ -4126,6 +4126,24 @@ public function testUnlinkHasManyNotCleanProperty() $this->assertFalse($author->dirty('articles')); } + /** + * Integration test for unlinking entities with HasMany. + * Checking that no error happens when the hasMany property is originally + * null + * + * @return void + */ + public function testUnlinkHasManyEmpty() + { + $authors = TableRegistry::get('Authors'); + $articles = TableRegistry::get('Articles'); + $authors->hasMany('Articles'); + $author = $authors->get(1); + $article = $authors->Articles->get(1); + + $authors->Articles->unlink($author, [$article]); + } + /** * Integration test for replacing entities which depend on their source entity with HasMany and failing transaction. False should be returned when