Browse Source

Merge pull request #5301 from cakephp/issue-5267

Fix notice error in ResultSet.
José Lorenzo Rodríguez 11 years ago
parent
commit
bb3701a1c7

+ 6 - 5
src/ORM/ResultSet.php

@@ -373,11 +373,13 @@ class ResultSet implements ResultSetInterface {
 			$results[$table][$field] = $value;
 		}
 
+		if (isset($presentAliases[$defaultAlias])) {
+			$results[$defaultAlias] = $this->_castValues(
+				$this->_defaultTable,
+				$results[$defaultAlias]
+			);
+		}
 		unset($presentAliases[$defaultAlias]);
-		$results[$defaultAlias] = $this->_castValues(
-			$this->_defaultTable,
-			$results[$defaultAlias]
-		);
 
 		$options = [
 			'useSetters' => false,
@@ -390,7 +392,6 @@ class ResultSet implements ResultSetInterface {
 			$alias = $assoc['nestKey'];
 			$instance = $assoc['instance'];
 
-			// Doing this before we're sure the root assoc has data is the problem.
 			if (!isset($results[$alias])) {
 				$results = $instance->defaultRowValue($results, $assoc['canBeJoined']);
 				continue;

+ 14 - 0
tests/TestCase/ORM/QueryRegressionTest.php

@@ -535,4 +535,18 @@ class QueryRegressionTest extends TestCase {
 		$this->assertEquals(2, $query->count());
 	}
 
+/**
+ * Integration test when selecting no fields on the primary table.
+ *
+ * @return void
+ */
+	public function testSelectNoFieldsOnPrimaryAlias() {
+		$table = TableRegistry::get('Articles');
+		$table->belongsTo('Users');
+		$query = $table->find()
+			->select(['Users__id' => 'id']);
+		$results = $query->toArray();
+		$this->assertCount(3, $results);
+	}
+
 }

+ 24 - 0
tests/TestCase/ORM/ResultSetTest.php

@@ -303,4 +303,28 @@ class ResultSetTest extends TestCase {
 		$this->assertNotEmpty($article['title']);
 	}
 
+/**
+ * Test that fetching rows does not fail when no fields were selected
+ * on the default alias.
+ *
+ * @return void
+ */
+	public function testFetchMissingDefaultAlias() {
+		$comments = TableRegistry::get('Comments');
+		$query = $comments->find();
+		$query->autoFields(false);
+
+		$row = ['Other__field' => 'test'];
+		$statement = $this->getMock('Cake\Database\StatementInterface');
+		$statement->method('fetch')
+			->will($this->onConsecutiveCalls($row, $row));
+		$statement->method('rowCount')
+			->will($this->returnValue(1));
+
+		$result = new ResultSet($query, $statement);
+
+		$result->valid();
+		$data = $result->current();
+	}
+
 }