Skip to content

Commit

Permalink
Making link() transational too
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Dec 15, 2013
1 parent fd5dd65 commit 53e6d87
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
19 changes: 14 additions & 5 deletions Cake/ORM/Association/BelongsToMany.php
Expand Up @@ -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);
}
);
}

/**
Expand Down Expand Up @@ -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')
Expand 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;
}
);
}
Expand Down
7 changes: 6 additions & 1 deletion Cake/Test/TestCase/ORM/Association/BelongsToManyTest.php
Expand Up @@ -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,
Expand Down

0 comments on commit 53e6d87

Please sign in to comment.