Skip to content
Permalink
Browse files

Contain the junction table when proxying finders.

When proxying finder methods from a belongstomany association, if that
association has conditions we should contain the junction table as the
conditions very likely use columns on that table.

Refs #7707
  • Loading branch information...
markstory committed Dec 3, 2015
1 parent 24718ff commit 88af5c27fa59bc13f0e0fb36b68936a50363f708
Showing with 52 additions and 0 deletions.
  1. +23 −0 src/ORM/Association/BelongsToMany.php
  2. +29 −0 tests/TestCase/ORM/Association/BelongsToManyTest.php
@@ -771,6 +771,29 @@ function () use ($sourceEntity, $targetEntities, $options) {
$sourceEntity->dirty($property, false);
}
/**
* Proxies the finding operation to the target table's find method
* and modifies the query accordingly based of this association
* configuration.
*
* If your association includes conditions, the junction table will be
* included in the query's contained associations.
*
* @param string|array $type the type of query to perform, if an array is passed,
* it will be interpreted as the `$options` parameter
* @param array $options The options to for the find
* @see \Cake\ORM\Table::find()
* @return \Cake\ORM\Query
*/
public function find($type = null, array $options = [])
{
$query = parent::find($type, $options);
if ($this->conditions()) {
$query->contain([$this->junction()->alias()]);
}
return $query;
}
/**
* Replaces existing association links between the source entity and the target
* with the ones passed. This method does a smart cleanup, links that are already
@@ -854,6 +854,35 @@ public function testReplaceLinkSuccess()
$this->assertFalse($entity->dirty('tags'));
}
/**
* Test that find() applies a contain() when the association uses conditions.
*
* @return void
*/
public function testFindAppliesContainWithConditions()
{
$connection = ConnectionManager::get('test');
$this->article->belongsToMany('Tags', [
'targetTable' => $this->tag,
'conditions' => ['ArticlesTags.favorite' => true]
]);
$query = $this->getMock(
'\Cake\ORM\Query',
[],
[$connection, $this->article]
);
$query->expects($this->once())
->method('where')
->with(['ArticlesTags.favorite' => true])
->will($this->returnSelf());
$query->expects($this->once())
->method('contain')
->with(['ArticlesTags'])
->will($this->returnSelf());
$this->tag->method('find')->will($this->returnValue($query));
$this->article->Tags->find();
}
/**
* Tests that replaceLinks() will contain() the target table when

0 comments on commit 88af5c2

Please sign in to comment.
You can’t perform that action at this time.