Skip to content

Commit

Permalink
Fixed eagerloading with matching and contain involving belongsTo asso…
Browse files Browse the repository at this point in the history
…ciations
  • Loading branch information
lorenzo committed Jan 31, 2015
1 parent 6aeb2ee commit a5f07bd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/ORM/EagerLoader.php
Expand Up @@ -496,13 +496,14 @@ public function loadExternal($query, $statement)
$instance = $meta->instance();
$config = $meta->config();
$alias = $instance->source()->alias();
$path = $meta->aliasPath();

$requiresKeys = $instance->requiresKeys($config);
if ($requiresKeys && empty($collected[$alias])) {
if ($requiresKeys && empty($collected[$path][$alias])) {
continue;
}

$keys = isset($collected[$alias]) ? $collected[$alias] : null;
$keys = isset($collected[$path][$alias]) ? $collected[$path][$alias] : null;
$f = $instance->eagerLoader(
$config + [
'query' => $query,
Expand Down Expand Up @@ -614,7 +615,7 @@ protected function _collectKeys($external, $query, $statement)
foreach ($keys as $key) {
$pkFields[] = key($query->aliasField($key, $alias));
}
$collectKeys[$alias] = [$alias, $pkFields, count($pkFields) === 1];
$collectKeys[$meta->aliasPath()] = [$alias, $pkFields, count($pkFields) === 1];
}

if (empty($collectKeys)) {
Expand All @@ -640,21 +641,21 @@ protected function _groupKeys($statement, $collectKeys)
{
$keys = [];
while ($result = $statement->fetch('assoc')) {
foreach ($collectKeys as $parts) {
foreach ($collectKeys as $nestKey => $parts) {
// Missed joins will have null in the results.
if ($parts[2] && !isset($result[$parts[1][0]])) {
continue;
}
if ($parts[2]) {
$keys[$parts[0]][] = $result[$parts[1][0]];
$keys[$nestKey][$parts[0]][] = $result[$parts[1][0]];
continue;
}

$collected = [];
foreach ($parts[1] as $key) {
$collected[] = $result[$key];
}
$keys[$parts[0]][] = $collected;
$keys[$nestKey][$parts[0]][] = $collected;
}
}

Expand Down
8 changes: 8 additions & 0 deletions tests/TestCase/ORM/QueryRegressionTest.php
Expand Up @@ -740,6 +740,12 @@ public function testQueryNotFatalError()
$comments->find()->contain('Deprs')->all();
}

/**
* Tests that using matching and contain on belongsTo associations
* works correctly.
*
* @return void
*/
public function testFindMatchingWithContain()
{
$comments = TableRegistry::get('Comments');
Expand All @@ -758,5 +764,7 @@ public function testFindMatchingWithContain()
->first();
$this->assertInstanceOf('Cake\ORM\Entity', $result->article);
$this->assertInstanceOf('Cake\ORM\Entity', $result->user);
$this->assertEquals(2, $result->user->id);
$this->assertEquals(1, $result->article->id);
}
}

0 comments on commit a5f07bd

Please sign in to comment.