diff --git a/Cake/Database/Type.php b/Cake/Database/Type.php index d5f62cbb771..0eb16486834 100644 --- a/Cake/Database/Type.php +++ b/Cake/Database/Type.php @@ -17,7 +17,6 @@ namespace Cake\Database; use Cake\Database\Driver; -use Exception; use PDO; /** diff --git a/Cake/ORM/Association/BelongsToMany.php b/Cake/ORM/Association/BelongsToMany.php index fce48ab25a9..2271e72e93f 100644 --- a/Cake/ORM/Association/BelongsToMany.php +++ b/Cake/ORM/Association/BelongsToMany.php @@ -484,8 +484,9 @@ public function replaceLinks(Entity $sourceEntity, array $targetEntities, array $primaryKey = (array)$this->source()->primaryKey(); $primaryValue = $sourceEntity->extract($primaryKey); - if (empty($primaryValue)) { - throw new \InvalidArgumentException; + if (count(array_filter($primaryValue, 'strlen')) !== count($primaryKey)) { + $message = __d('cake_dev', 'Could not find primary key value for source entity'); + throw new \InvalidArgumentException($message); } return $this->junction()->connection()->transactional( diff --git a/Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php b/Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php index 8d37712b71b..eaf1ddbea1b 100644 --- a/Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php +++ b/Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php @@ -899,4 +899,23 @@ public function testUnlinkWithoutPropertyClean() { $this->assertEquals($tags, $entity->get('test')); } +/** + * Test liking entities having a non persited source entity + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Could not find primary key value for source entity + * @return void + */ + public function testRplaceWithMissingPrimaryKey() { + $config = [ + 'sourceTable' => $this->article, + 'targetTable' => $this->tag, + 'joinTable' => 'tags_articles' + ]; + $assoc = new BelongsToMany('Test', $config); + $entity = new Entity(['foo' => 1], ['markNew' => false]); + $tags = [new Entity(['id' => 2]), new Entity(['id' => 3])]; + $assoc->replaceLinks($entity, $tags); + } + }