Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Fixing hydration fro deeply nested associations
  • Loading branch information
lorenzo committed Sep 15, 2013
1 parent f0bb2f5 commit d065784
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 10 deletions.
4 changes: 3 additions & 1 deletion lib/Cake/ORM/Association.php
Expand Up @@ -394,7 +394,9 @@ public function attachTo(Query $query, array $options = []) {
public function transformRow($row) {
$sourceAlias = $this->source()->alias();
$targetAlias = $this->target()->alias();
$row[$sourceAlias][$this->property()] = $row[$targetAlias];
if (isset($row[$sourceAlias])) {
$row[$sourceAlias][$this->property()] = $row[$targetAlias];
}
return $row;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/Cake/ORM/ResultSet.php
Expand Up @@ -270,7 +270,7 @@ protected function _groupResult($row) {
}

$results = $results[$defaultAlias];
if ($this->_hydrate) {
if ($this->_hydrate && !($results instanceof Entity)) {
$results = (new Entity)->set($results, false);
}
return $results;
Expand Down
40 changes: 32 additions & 8 deletions lib/Cake/Test/TestCase/ORM/QueryTest.php
Expand Up @@ -489,10 +489,7 @@ public function testHasManyEagerLoadingDeep($strategy) {
],
[
'id' => 2,
'name' => 'nate',
'articles' => [
'author' => ['id' => 2, 'name' => 'nate']
]
'name' => 'nate'
],
[
'id' => 3,
Expand All @@ -510,10 +507,7 @@ public function testHasManyEagerLoadingDeep($strategy) {
],
[
'id' => 4,
'name' => 'garrett',
'articles' => [
'author' => ['id' => 4, 'name' => 'garrett']
]
'name' => 'garrett'
]
];
$this->assertEquals($expected, $results);
Expand Down Expand Up @@ -1227,4 +1221,34 @@ public function testHydrateBelongsTo() {
$this->assertEquals($expected, $first->author->toArray());
}

/**
* Tests that deeply nested associations are also hydrated correctly
*
* @return void
*/
public function testHydrateDeep() {
$this->_createTables();

$table = Table::build('author', ['connection' => $this->connection]);
$article = Table::build('article', ['connection' => $this->connection]);
$table->hasMany('article', [
'property' => 'articles',
'sort' => ['article.id' => 'asc']
]);
$article->belongsTo('author');
$query = new Query($this->connection, $table);

$results = $query->select()
->contain(['article' => ['author']])
->hydrate(true)
->toArray();

$this->assertCount(4, $results);
$first = $results[0];
$this->assertInstanceOf('\Cake\ORM\Entity', $first->articles[0]->author);
$expected = ['id' => 1, 'name' => 'mariano'];
$this->assertEquals($expected, $first->articles[0]->author->toArray());
$this->assertFalse(isset($results[3]->articles));
}

}

0 comments on commit d065784

Please sign in to comment.