Skip to content

Commit

Permalink
Avoid selecting all fields if possible when using find('list').
Browse files Browse the repository at this point in the history
Closes #6186.
  • Loading branch information
ADmad committed Apr 27, 2015
1 parent d4e0e0a commit ec8f1a1
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/ORM/Table.php
Expand Up @@ -968,6 +968,14 @@ public function findList(Query $query, array $options)
trigger_error('Option "idField" is deprecated, use "keyField" instead.', E_USER_WARNING);
}

if (!$query->clause('select')) {
$fields = array_merge((array)$options['keyField'], (array)$options['valueField']);
$columns = $this->schema()->columns();
if (count($fields) === count(array_intersect($fields, $columns))) {
$query->select($fields);
}
}

$options = $this->_setFieldMatchers(
$options,
['keyField', 'valueField', 'groupField']
Expand Down
61 changes: 61 additions & 0 deletions tests/TestCase/ORM/TableTest.php
Expand Up @@ -1180,6 +1180,67 @@ public function testFindListHydrated()
$this->assertSame($expected, $query->toArray());
}

/**
* Test that find('list') only selects required fields.
*
* @return void
*/
public function testFindListSelectedFields()
{
$table = new Table([
'table' => 'users',
'connection' => $this->connection,
]);
$table->displayField('username');

$query = $table->find('list');
$expected = ['id', 'username'];
$this->assertSame($expected, $query->clause('select'));

$select = ['odd' => new QueryExpression('id % 2')];
$query = $table->find('list', ['groupField' => 'odd'])
->select($select)
->order('id');
$expected = array_merge(['id', 'username'], $select);
$this->assertSame($expected, $query->clause('select'));

$expected = ['odd' => new QueryExpression('id % 2'), 'id', 'username'];
$query = $table->find('list', [
'fields' => $expected,
'groupField' => 'odd',
]);
$this->assertSame($expected, $query->clause('select'));
}

/**
* test that find('list') does not auto add fields to select if using virtual properties
*
* @return void
*/
public function testFindListWithVirtualField()
{
$table = new Table([
'table' => 'users',
'connection' => $this->connection,
'entityClass' => '\TestApp\Model\Entity\VirtualUser'
]);
$table->displayField('bonus');

$query = $table
->find('list')
->order('id');

$this->assertEmpty($query->clause('select'));

$expected = [
1 => 'bonus',
2 => 'bonus',
3 => 'bonus',
4 => 'bonus'
];
$this->assertSame($expected, $query->toArray());
}

/**
* Test the default entityClass.
*
Expand Down

0 comments on commit ec8f1a1

Please sign in to comment.