Skip to content

Commit

Permalink
Merge pull request #9337 from cakephp/issue-9326
Browse files Browse the repository at this point in the history
Fix computed fields in contained associations
  • Loading branch information
lorenzo committed Aug 24, 2016
2 parents c0b4f9d + 06d7ba5 commit be2f7f1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/ORM/Association/SelectableAssociationTrait.php
Expand Up @@ -134,12 +134,21 @@ protected function _assertFieldsPresent($fetchQuery, $key)
if (empty($select)) {
return;
}
$missingFields = array_diff($key, $select) !== [];
$missingKey = function ($fieldList, $key) {
foreach ($key as $keyField) {
if (!in_array($keyField, $fieldList, true)) {
return true;
}
}

return false;
};

$missingFields = $missingKey($select, $key);
if ($missingFields) {
$driver = $fetchQuery->connection()->driver();
$quoted = array_map([$driver, 'quoteIdentifier'], $key);
$missingFields = array_diff($quoted, $select) !== [];
$missingFields = $missingKey($select, $quoted);
}

if ($missingFields) {
Expand Down
26 changes: 26 additions & 0 deletions tests/TestCase/ORM/QueryRegressionTest.php
Expand Up @@ -947,6 +947,32 @@ public function testContainWithNoFields()
$this->assertEquals([3 => 1, 4 => 1, 5 => 1], $results->toArray());
}

/**
* Tests that find() and contained associations using computed fields doesn't error out.
*
* @see https://github.com/cakephp/cakephp/issues/9326
* @return void
*/
public function testContainWithComputedField()
{
$this->loadFixtures('Comments', 'Users');
$table = TableRegistry::get('Users');
$table->hasMany('Comments');

$query = $table->find()->contain([
'Comments' => function ($q) {
return $q->select([
'concat' => $q->func()->concat(['red', 'blue']),
'user_id'
]);
}])
->where(['Users.id' => 2]);

$results = $query->toArray();
$this->assertCount(1, $results);
$this->assertEquals('redblue', $results[0]->comments[0]->concat);
}

/**
* Tests that using matching and selecting no fields for that association
* will no trigger any errors and fetch the right results
Expand Down

0 comments on commit be2f7f1

Please sign in to comment.