Skip to content

Commit

Permalink
Add support for DISTINCT clause
Browse files Browse the repository at this point in the history
  • Loading branch information
bingo-soft committed Oct 12, 2019
1 parent 81922a2 commit ce6b7f9
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
15 changes: 15 additions & 0 deletions docs/en/reference/query-builder.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,21 @@ and ``delete($tableName)``:
You can convert a query builder to its SQL string representation
by calling ``$queryBuilder->getSQL()`` or casting the object to string.

DISTINCT-Clause
~~~~~~~~~~~~~~~

The ``SELECT`` statement can be specified with a ``DISTINCT`` clause:

.. code-block:: php
<?php
$queryBuilder
->select('name')
->distinct()
->from('users')
;
WHERE-Clause
~~~~~~~~~~~~

Expand Down
23 changes: 22 additions & 1 deletion lib/Doctrine/DBAL/Query/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class QueryBuilder
*/
private $sqlParts = [
'select' => [],
'distinct' => false,
'from' => [],
'join' => [],
'set' => [],
Expand Down Expand Up @@ -469,6 +470,25 @@ public function select($select = null)
return $this->add('select', $selects);
}

/**
* Adds DISTINCT to the query.
*
* <code>
* $qb = $conn->createQueryBuilder()
* ->select('u.id')
* ->distinct()
* ->from('users', 'u')
* </code>
*
* @return $this This QueryBuilder instance.
*/
public function distinct() : self
{
$this->sqlParts['distinct'] = true;

return $this;
}

/**
* Adds an item that is to be returned in the query result.
*
Expand Down Expand Up @@ -1098,7 +1118,8 @@ public function resetQueryPart($queryPartName)
*/
private function getSQLForSelect()
{
$query = 'SELECT ' . implode(', ', $this->sqlParts['select']);
$query = 'SELECT ' . ($this->sqlParts['distinct'] ? 'DISTINCT ' : '') .
implode(', ', $this->sqlParts['select']);

$query .= ($this->sqlParts['from'] ? ' FROM ' . implode(', ', $this->getFromClauses()) : '')
. ($this->sqlParts['where'] !== null ? ' WHERE ' . ((string) $this->sqlParts['where']) : '')
Expand Down
11 changes: 11 additions & 0 deletions tests/Doctrine/Tests/DBAL/Query/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ public function testSimpleSelect() : void
self::assertEquals('SELECT u.id FROM users u', (string) $qb);
}

public function testSimpleSelectWithDistinct() : void
{
$qb = new QueryBuilder($this->conn);

$qb->select('u.id')
->distinct()
->from('users', 'u');

self::assertEquals('SELECT DISTINCT u.id FROM users u', (string) $qb);
}

public function testSelectWithSimpleWhere() : void
{
$qb = new QueryBuilder($this->conn);
Expand Down

0 comments on commit ce6b7f9

Please sign in to comment.