Skip to content

Commit

Permalink
Making it easy to prevent association fields be selected by default
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed May 4, 2013
1 parent 5d54978 commit efb395f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/Cake/ORM/Query.php
Expand Up @@ -11,6 +11,8 @@ class Query extends DatabaseQuery {

protected $_containments;

protected $_hasFields;

public function repository(Table $table = null) {
if ($table === null) {
return $this->_table;
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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');
}
Expand Down
20 changes: 20 additions & 0 deletions lib/Cake/Test/TestCase/ORM/QueryTest.php
Expand Up @@ -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);
}
}

0 comments on commit efb395f

Please sign in to comment.