Browse Source

Merge pull request #7160 from antograssiot/3.1-issue-7150

allow string to be passed to `Cake\Database\Query::distinct()`
Mark Story 10 years ago
parent
commit
c79a1062f3
2 changed files with 20 additions and 1 deletions
  1. 5 1
      src/Database/Query.php
  2. 15 0
      tests/TestCase/Database/QueryTest.php

+ 5 - 1
src/Database/Query.php

@@ -299,12 +299,14 @@ class Query implements ExpressionInterface, IteratorAggregate
      *
      * // Filters products in the same city
      * $query->distinct(['city']);
+     * $query->distinct('city');
      *
      * // Filter products with the same name
      * $query->distinct(['name'], true);
+     * $query->distinct('name', true);
      * ```
      *
-     * @param array|ExpressionInterface $on fields to be filtered on
+     * @param array|ExpressionInterface|string $on fields to be filtered on
      * @param bool $overwrite whether to reset fields with passed list or not
      * @return $this
      */
@@ -312,6 +314,8 @@ class Query implements ExpressionInterface, IteratorAggregate
     {
         if ($on === []) {
             $on = true;
+        } elseif (is_string($on)) {
+            $on = [$on];
         }
 
         if (is_array($on)) {

+ 15 - 0
tests/TestCase/Database/QueryTest.php

@@ -1543,6 +1543,21 @@ class QueryTest extends TestCase
             [3, 1],
             collection($results)->sortBy('author_id')->extract('author_id')->toList()
         );
+
+        $query = new Query($this->connection);
+        $result = $query
+            ->select(['id', 'author_id'])
+            ->distinct('author_id')
+            ->from(['a' => 'articles'])
+            ->order(['author_id' => 'ASC'])
+            ->execute();
+        $this->assertCount(2, $result);
+        $results = $result->fetchAll('assoc');
+        $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
+        $this->assertEquals(
+            [3, 1],
+            collection($results)->sortBy('author_id')->extract('author_id')->toList()
+        );
     }
 
     /**