Browse Source

Make select() accept a Table or Association instance

Closes #6103
Jose Lorenzo Rodriguez 10 years ago
parent
commit
812430d5ab
2 changed files with 53 additions and 0 deletions
  1. 24 0
      src/ORM/Query.php
  2. 29 0
      tests/TestCase/ORM/QueryTest.php

+ 24 - 0
src/ORM/Query.php

@@ -125,6 +125,30 @@ class Query extends DatabaseQuery implements JsonSerializable
     }
 
     /**
+     * {@inheritDocs}
+     *
+     * If you pass an instance of a `Cake\ORM\Table` or `Cake\ORM\Association` class,
+     * all the fields in the schema of the table or the association will be added to
+     * the select clause.
+     *
+     * @param array|ExpressionInterface|string|\Cake\ORM\Table|\Cake\ORM\Association $fields fields
+     * to be added to the list.
+     * @param bool $overwrite whether to reset fields with passed list or not
+     */
+    public function select($fields = [], $overwrite = false)
+    {
+        if ($fields instanceof Association) {
+            $fields = $fields->target();
+        }
+
+        if ($fields instanceof Table) {
+            $fields = $this->aliasFields($fields->schema()->columns(), $fields->alias());
+        }
+
+        return parent::select($fields, $overwrite);
+    }
+
+    /**
      * Hints this object to associate the correct types when casting conditions
      * for the database. This is done by extracting the field types from the schema
      * associated to the passed table object. This prevents the user from repeating

+ 29 - 0
tests/TestCase/ORM/QueryTest.php

@@ -2650,6 +2650,35 @@ class QueryTest extends TestCase
         $this->assertEquals(2, $result->_matchingData['tags']->id);
     }
 
+     /**
+     * Tests that select() can be called with Table and Association
+     * instance
+     *
+     * @return void
+     */
+    public function testSelectWithTableAndAssociationInstance()
+    {
+        $table = TableRegistry::get('articles');
+        $table->belongsTo('authors');
+        $result = $table
+            ->find()
+            ->select(['foo' => 'Authors.id'])
+            ->select($table)
+            ->select($table->authors)
+            ->contain(['authors'])
+            ->first();
+
+        $expected = $table
+            ->find()
+            ->select(['foo' => 'Authors.id'])
+            ->autoFields(true)
+            ->contain(['authors'])
+            ->first();
+
+        $this->assertNotEmpty($result);
+        $this->assertEquals($expected, $result);
+    }
+
     /**
      * Tests that isEmpty() can be called on a query
      *