Skip to content

Commit

Permalink
Adding tests for chaining contain in query builders
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Feb 9, 2014
1 parent 9937703 commit 3cd5aec
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/ORM/Association.php
Expand Up @@ -384,6 +384,8 @@ protected function _options(array $options) {
* will be merged with any conditions originally configured for this association
* - fields: a list of fields in the target table to include in the result
* - type: The type of join to be used (e.g. INNER)
* - matching: Indicates whether the query records should be filtered based on
* the records found on this association. This will force a 'INNER JOIN'
*
* @param Query $query the query to be altered to include the target table data
* @param array $options Any extra options or overrides to be taken in account
Expand All @@ -398,7 +400,7 @@ public function attachTo(Query $query, array $options = []) {
'foreignKey' => $this->foreignKey(),
'conditions' => [],
'fields' => [],
'type' => $this->joinType(),
'type' => empty($options['matching']) ? $this->joinType() : 'INNER',
'table' => $target->table()
];
$options['conditions'] = array_merge($this->conditions(), $options['conditions']);
Expand Down
43 changes: 43 additions & 0 deletions tests/TestCase/ORM/QueryTest.php
Expand Up @@ -1690,4 +1690,47 @@ public function testFormatDeepDistantAssociationRecords() {
$this->assertEquals($expected, $query->toArray());
}

/**
* Tests that it is possible to attach more association when using a query
* builder for other associaitons
*
* @return void
*/
public function testContainInAssociationQuery() {
$table = TableRegistry::get('ArticlesTags');
$table->belongsTo('Articles');
$table->association('Articles')->target()->belongsTo('Authors');

$query = $table->find()->contain(['Articles' => function($q) {
return $q->contain('Authors');
}]);
$results = $query->extract('article.author.name')->toArray();
$expected = ['mariano', 'mariano', 'larry', 'larry'];
$this->assertEquals($expected, $results);
}

/**
* Tests that it is possible to apply more `matching` conditions inside query
* builders for associations
*
* @return void
*/
public function testContainInAssociationMatching() {
$table = TableRegistry::get('authors');
$table->hasMany('articles');
$articles = $table->association('articles')->target();
$articles->hasMany('articlesTags');
$articles->association('articlesTags')->target()->belongsTo('tags');

$query = $table->find()->matching('articles.articlesTags', function($q) {
return $q->matching('tags', function($q) {
return $q->where(['tags.name' => 'tag3']);
});
});

$results = $query->toArray();
$this->assertCount(1, $results);
$this->assertEquals('tag3', $results[0]->articles->articles_tags->tag->name);
}

}

0 comments on commit 3cd5aec

Please sign in to comment.