Browse Source

Adding tests for chaining contain in query builders

Jose Lorenzo Rodriguez 12 years ago
parent
commit
3cd5aec1c3
2 changed files with 46 additions and 1 deletions
  1. 3 1
      src/ORM/Association.php
  2. 43 0
      tests/TestCase/ORM/QueryTest.php

+ 3 - 1
src/ORM/Association.php

@@ -384,6 +384,8 @@ abstract class Association {
  *   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
@@ -398,7 +400,7 @@ abstract class Association {
 			'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']);

+ 43 - 0
tests/TestCase/ORM/QueryTest.php

@@ -1690,4 +1690,47 @@ class QueryTest extends TestCase {
 		$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);
+	}
+
 }