From efb395f97ae2fa313ecbee1fd87a7866f23ae765 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Sat, 4 May 2013 20:54:11 +0200 Subject: [PATCH] Making it easy to prevent association fields be selected by default --- lib/Cake/ORM/Query.php | 12 ++++++++++-- lib/Cake/Test/TestCase/ORM/QueryTest.php | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/lib/Cake/ORM/Query.php b/lib/Cake/ORM/Query.php index a40affb3bfc..65d689a0ef5 100644 --- a/lib/Cake/ORM/Query.php +++ b/lib/Cake/ORM/Query.php @@ -11,6 +11,8 @@ class Query extends DatabaseQuery { protected $_containments; + protected $_hasFields; + public function repository(Table $table = null) { if ($table === null) { return $this->_table; @@ -119,9 +121,13 @@ protected function _normalizeContain(Table $parent, $alias, $options) { ]; $config = $this->_resolveForeignKeyConditions($table, $parent, $config); - if (empty($config['fields']) || $config['fields'] !== false) { - $config['fields'] = array_keys($table->schema()); + if (empty($config['fields'])) { + $f = isset($config['fields']) ? $config['fields'] : null; + if (!$this->_hasFields && ($f === null || $f !== false)) { + $config['fields'] = array_keys($table->schema()); + } } + foreach ($extra as $t => $assoc) { $config['associations'][$t] = $this->_normalizeContain($table, $t, $assoc); } @@ -192,8 +198,10 @@ protected function _aliasFields($fields, $defaultAlias = null) { protected function _addDefaultFields() { $select = $this->clause('select'); + $this->_hasFields = true; if (!count($select)) { + $this->_hasFields = false; $this->select(array_keys($this->repository()->schema())); $select = $this->clause('select'); } diff --git a/lib/Cake/Test/TestCase/ORM/QueryTest.php b/lib/Cake/Test/TestCase/ORM/QueryTest.php index 11e9c8a2de8..185247b4db5 100644 --- a/lib/Cake/Test/TestCase/ORM/QueryTest.php +++ b/lib/Cake/Test/TestCase/ORM/QueryTest.php @@ -202,5 +202,25 @@ public function testContainToFieldsDefault() { 'order__placed' => 'order.placed' ]; $this->assertEquals($expected, $select); + + $contains['client']['fields'] = ['name']; + $query = new Query($this->connection); + $query->select('foo.id')->repository($table)->contain($contains)->sql(); + $select = $query->clause('select'); + $expected = ['foo__id' => 'foo.id', 'client__name' => 'client.name']; + $this->assertEquals($expected, $select); + + $contains['client']['fields'] = []; + $contains['client']['order']['fields'] = false; + $query = new Query($this->connection); + $query->select()->repository($table)->contain($contains)->sql(); + $select = $query->clause('select'); + $expected = [ + 'foo__id' => 'foo.id', + 'client__id' => 'client.id', + 'client__name' => 'client.name', + 'client__phone' => 'client.phone', + ]; + $this->assertEquals($expected, $select); } }