Skip to content

Commit

Permalink
Merge pull request cakephp#7626 from beporter/belongstomany-condition…
Browse files Browse the repository at this point in the history
…s-on-target

Contain target table in BelongsToMany::replaceLinks() when conditions present.
  • Loading branch information
markstory committed Nov 3, 2015
2 parents 5e6254a + 16216c0 commit 8ac7627
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/ORM/Association/BelongsToMany.php
Expand Up @@ -758,6 +758,7 @@ function () use ($sourceEntity, $targetEntities, $primaryValue, $options) {

$associationConditions = $this->conditions();
if ($associationConditions) {
$existing->contain($this->target()->alias());
$existing->andWhere($associationConditions);
}

Expand Down
63 changes: 63 additions & 0 deletions tests/TestCase/ORM/Association/BelongsToManyTest.php
Expand Up @@ -828,6 +828,69 @@ public function testReplaceLinkSuccess()
$this->assertFalse($entity->dirty('tags'));
}


/**
* Tests that replaceLinks() will contain() the target table when
* there are conditions present on the association.
*
* @return void
*/
public function testReplaceLinkWithConditions()
{
$connection = ConnectionManager::get('test');
$joint = $this->getMock(
'\Cake\ORM\Table',
['find'],
[['alias' => 'ArticlesTags', 'connection' => $connection]]
);
$config = [
'sourceTable' => $this->article,
'targetTable' => $this->tag,
'through' => $joint,
'joinTable' => 'tags_articles',
'conditions' => ['Tags.id' => 'blah'],
];
$assoc = $this->getMock(
'\Cake\ORM\Association\BelongsToMany',
['_collectJointEntities'],
['tags', $config]
);
$assoc->junction();

$query1 = $this->getMock(
'\Cake\ORM\Query',
['where', 'andWhere', 'addDefaultTypes', 'contain'],
[$connection, $joint]
);
$query1->expects($this->at(0))
->method('where')
->will($this->returnSelf());
$query1->expects($this->at(1))
->method('where')
->will($this->returnSelf());
$query1->expects($this->at(2))
->method('contain')
->with('Tags')
->will($this->returnSelf());
$query1->expects($this->at(3))
->method('andWhere')
->with($config['conditions'])
->will($this->returnSelf());
$query1->setResult(new \ArrayIterator([]));

$joint->expects($this->at(0))->method('find')
->with('all')
->will($this->returnValue($query1));

$entity = new Entity(['id' => 1, 'test' => []]);

$assoc->expects($this->once())->method('_collectJointEntities')
->with($entity, [])
->will($this->returnValue([]));

$assoc->replaceLinks($entity, [], ['associated' => false]);
}

/**
* Provider for empty values
*
Expand Down

0 comments on commit 8ac7627

Please sign in to comment.