File tree Expand file tree Collapse file tree 3 files changed +48
-1
lines changed
tests/Doctrine/Tests/DBAL/Query Expand file tree Collapse file tree 3 files changed +48
-1
lines changed Original file line number Diff line number Diff line change @@ -87,6 +87,21 @@ and ``delete($tableName)``:
87
87
You can convert a query builder to its SQL string representation
88
88
by calling ``$queryBuilder->getSQL() `` or casting the object to string.
89
89
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
+
90
105
WHERE-Clause
91
106
~~~~~~~~~~~~
92
107
Original file line number Diff line number Diff line change @@ -59,6 +59,7 @@ class QueryBuilder
59
59
*/
60
60
private $ sqlParts = [
61
61
'select ' => [],
62
+ 'distinct ' => false ,
62
63
'from ' => [],
63
64
'join ' => [],
64
65
'set ' => [],
@@ -469,6 +470,25 @@ public function select($select = null)
469
470
return $ this ->add ('select ' , $ selects );
470
471
}
471
472
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
+
472
492
/**
473
493
* Adds an item that is to be returned in the query result.
474
494
*
@@ -1098,7 +1118,8 @@ public function resetQueryPart($queryPartName)
1098
1118
*/
1099
1119
private function getSQLForSelect ()
1100
1120
{
1101
- $ query = 'SELECT ' . implode (', ' , $ this ->sqlParts ['select ' ]);
1121
+ $ query = 'SELECT ' . ($ this ->sqlParts ['distinct ' ] ? 'DISTINCT ' : '' ) .
1122
+ implode (', ' , $ this ->sqlParts ['select ' ]);
1102
1123
1103
1124
$ query .= ($ this ->sqlParts ['from ' ] ? ' FROM ' . implode (', ' , $ this ->getFromClauses ()) : '' )
1104
1125
. ($ this ->sqlParts ['where ' ] !== null ? ' WHERE ' . ((string ) $ this ->sqlParts ['where ' ]) : '' )
Original file line number Diff line number Diff line change @@ -50,6 +50,17 @@ public function testSimpleSelect() : void
50
50
self ::assertEquals ('SELECT u.id FROM users u ' , (string ) $ qb );
51
51
}
52
52
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
+
53
64
public function testSelectWithSimpleWhere () : void
54
65
{
55
66
$ qb = new QueryBuilder ($ this ->conn );
You can’t perform that action at this time.
0 commit comments