Skip to content

Commit ce6b7f9

Browse files
committed
Add support for DISTINCT clause
1 parent 81922a2 commit ce6b7f9

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

docs/en/reference/query-builder.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,21 @@ and ``delete($tableName)``:
8787
You can convert a query builder to its SQL string representation
8888
by calling ``$queryBuilder->getSQL()`` or casting the object to string.
8989

90+
DISTINCT-Clause
91+
~~~~~~~~~~~~~~~
92+
93+
The ``SELECT`` statement can be specified with a ``DISTINCT`` clause:
94+
95+
.. code-block:: php
96+
97+
<?php
98+
99+
$queryBuilder
100+
->select('name')
101+
->distinct()
102+
->from('users')
103+
;
104+
90105
WHERE-Clause
91106
~~~~~~~~~~~~
92107

lib/Doctrine/DBAL/Query/QueryBuilder.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ class QueryBuilder
5959
*/
6060
private $sqlParts = [
6161
'select' => [],
62+
'distinct' => false,
6263
'from' => [],
6364
'join' => [],
6465
'set' => [],
@@ -469,6 +470,25 @@ public function select($select = null)
469470
return $this->add('select', $selects);
470471
}
471472

473+
/**
474+
* Adds DISTINCT to the query.
475+
*
476+
* <code>
477+
* $qb = $conn->createQueryBuilder()
478+
* ->select('u.id')
479+
* ->distinct()
480+
* ->from('users', 'u')
481+
* </code>
482+
*
483+
* @return $this This QueryBuilder instance.
484+
*/
485+
public function distinct() : self
486+
{
487+
$this->sqlParts['distinct'] = true;
488+
489+
return $this;
490+
}
491+
472492
/**
473493
* Adds an item that is to be returned in the query result.
474494
*
@@ -1098,7 +1118,8 @@ public function resetQueryPart($queryPartName)
10981118
*/
10991119
private function getSQLForSelect()
11001120
{
1101-
$query = 'SELECT ' . implode(', ', $this->sqlParts['select']);
1121+
$query = 'SELECT ' . ($this->sqlParts['distinct'] ? 'DISTINCT ' : '') .
1122+
implode(', ', $this->sqlParts['select']);
11021123

11031124
$query .= ($this->sqlParts['from'] ? ' FROM ' . implode(', ', $this->getFromClauses()) : '')
11041125
. ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '')

tests/Doctrine/Tests/DBAL/Query/QueryBuilderTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,17 @@ public function testSimpleSelect() : void
5050
self::assertEquals('SELECT u.id FROM users u', (string) $qb);
5151
}
5252

53+
public function testSimpleSelectWithDistinct() : void
54+
{
55+
$qb = new QueryBuilder($this->conn);
56+
57+
$qb->select('u.id')
58+
->distinct()
59+
->from('users', 'u');
60+
61+
self::assertEquals('SELECT DISTINCT u.id FROM users u', (string) $qb);
62+
}
63+
5364
public function testSelectWithSimpleWhere() : void
5465
{
5566
$qb = new QueryBuilder($this->conn);

0 commit comments

Comments
 (0)