Browse Source

Fixing bug in formatResults in the query builder for belongsTo association and adding test

Jose Lorenzo Rodriguez 12 years ago
parent
commit
8ff4eaee16
2 changed files with 38 additions and 1 deletions
  1. 10 1
      src/ORM/Association.php
  2. 28 0
      tests/TestCase/ORM/QueryTest.php

+ 10 - 1
src/ORM/Association.php

@@ -16,6 +16,7 @@ namespace Cake\ORM;
 
 use Cake\Event\Event;
 use Cake\ORM\Entity;
+use Cake\ORM\Query;
 use Cake\ORM\Table;
 use Cake\ORM\TableRegistry;
 use Cake\Utility\Inflector;
@@ -387,6 +388,8 @@ abstract class Association {
  * @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
  * @return void
+ * @throws \RuntimeException if the query builder passed does not return a query
+ * object
  */
 	public function attachTo(Query $query, array $options = []) {
 		$target = $this->target();
@@ -412,6 +415,12 @@ abstract class Association {
 
 		if (!empty($options['queryBuilder'])) {
 			$dummy = $options['queryBuilder']($dummy);
+			if (!($dummy instanceof Query)) {
+				throw new \RuntimeException(sprintf(
+					'Query builder for association "%s" did not return a query',
+					$this->name()
+				));
+			}
 		}
 
 		$this->_dispatchBeforeFind($dummy);
@@ -510,7 +519,7 @@ abstract class Association {
 				$extracted = new ResultSetDecorator($callable($extracted));
 			}
 			return $results->insert($property, $extracted);
-		});
+		}, Query::PREPEND);
 	}
 
 	protected function _bindNewAssociations($query, $surrogate, $options) {

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

@@ -1580,4 +1580,32 @@ class QueryTest extends TestCase {
 		$this->assertEquals(3, $query->count());
 	}
 
+/**
+ * Tests that it is possible to apply formatters inside the query builder
+ * for belongsTo associations
+ *
+ * @return void
+ */
+	public function testFormatBelongsToRecords() {
+		$table = TableRegistry::get('articles');
+		$table->belongsTo('authors');
+
+		$query = $table->find()
+			->contain(['authors' => function($q) {
+				return $q->formatResults(function($authors) {
+					return $authors->map(function($author) {
+						$author->idCopy = $author->id;
+						return $author;
+					});
+				});
+			}]);
+	
+		$query->formatResults(function($results) {
+			return $results->combine('id', 'author.idCopy');
+		});
+		$results = $query->toArray();
+		$expected = [1 => 1, 2 => 3, 3 => 1];
+		$this->assertEquals($expected, $results);
+	}
+
 }