diff --git a/Cake/ORM/Association/BelongsToMany.php b/Cake/ORM/Association/BelongsToMany.php index 2d67bc852bd..fce48ab25a9 100644 --- a/Cake/ORM/Association/BelongsToMany.php +++ b/Cake/ORM/Association/BelongsToMany.php @@ -421,7 +421,12 @@ public function link(Entity $sourceEntity, array $targetEntities, array $options $links = $sourceEntity->get($property) ?: []; $links = array_merge($links, $targetEntities); $sourceEntity->set($property, $links); - return $this->_saveLinks($sourceEntity, $targetEntities, $options); + + return $this->junction()->connection()->transactional( + function() use ($sourceEntity, $targetEntities, $options) { + return $this->_saveLinks($sourceEntity, $targetEntities, $options); + } + ); } /** @@ -483,7 +488,7 @@ public function replaceLinks(Entity $sourceEntity, array $targetEntities, array throw new \InvalidArgumentException; } - $this->junction()->connection()->transactional( + return $this->junction()->connection()->transactional( function() use ($sourceEntity, $targetEntities, $primaryValue, $options) { $foreignKey = (array)$this->foreignKey(); $existing = $this->_junctionTable->find('all') @@ -495,10 +500,14 @@ function() use ($sourceEntity, $targetEntities, $primaryValue, $options) { $property = $this->property(); $sourceEntity->set($property, $inserts); - if ($this->save($sourceEntity, $options + ['associated' => false])) { - $sourceEntity->set($property, $targetEntities); - $sourceEntity->dirty($property, false); + + if ($inserts && !$this->save($sourceEntity, $options + ['associated' => false])) { + return false; } + + $sourceEntity->set($property, $targetEntities); + $sourceEntity->dirty($property, false); + return true; } ); } diff --git a/Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php b/Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php index f7631a4fcd8..8d37712b71b 100644 --- a/Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php +++ b/Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php @@ -683,7 +683,12 @@ public function testLinkWithNotPersistedTarget() { * @return void */ public function testLinkSuccess() { - $joint = $this->getMock('\Cake\ORM\Table', ['save'], [['alias' => 'ArticlesTags']]); + $connection = \Cake\Database\ConnectionManager::get('test'); + $joint = $this->getMock( + '\Cake\ORM\Table', + ['save'], + [['alias' => 'ArticlesTags', 'connection' => $connection]] + ); $config = [ 'sourceTable' => $this->article, 'targetTable' => $this->tag,