Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixing bug in formatResults in the query builder for belongsTo associ…

…ation and adding test
  • Loading branch information...
commit 8ff4eaee164f0ef0501a65401a235089851f1907 1 parent 1538bd3
@lorenzo lorenzo authored
Showing with 38 additions and 1 deletion.
  1. +10 −1 src/ORM/Association.php
  2. +28 −0 tests/TestCase/ORM/QueryTest.php
View
11 src/ORM/Association.php
@@ -16,6 +16,7 @@
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 @@ protected function _options(array $options) {
* @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 @@ public function attachTo(Query $query, array $options = []) {
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 @@ protected function _formatAssociationResults($query, $surrogate) {
$extracted = new ResultSetDecorator($callable($extracted));
}
return $results->insert($property, $extracted);
- });
+ }, Query::PREPEND);
}
protected function _bindNewAssociations($query, $surrogate, $options) {
View
28 tests/TestCase/ORM/QueryTest.php
@@ -1580,4 +1580,32 @@ public function testCountWithContainCallingAll() {
$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);
+ }
+
}
Please sign in to comment.
Something went wrong with that request. Please try again.