diff --git a/src/ORM/Table.php b/src/ORM/Table.php index f9a01e163c6..ec867333ae6 100644 --- a/src/ORM/Table.php +++ b/src/ORM/Table.php @@ -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'] diff --git a/tests/TestCase/ORM/TableTest.php b/tests/TestCase/ORM/TableTest.php index 641693372b7..ac443875965 100644 --- a/tests/TestCase/ORM/TableTest.php +++ b/tests/TestCase/ORM/TableTest.php @@ -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. *