1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link http://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license http://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\db; |
9
|
|
|
|
10
|
|
|
use Yii; |
11
|
|
|
use yii\base\Component; |
12
|
|
|
use yii\base\InvalidConfigException; |
13
|
|
|
use yii\base\InvalidParamException; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Query represents a SELECT SQL statement in a way that is independent of DBMS. |
17
|
|
|
* |
18
|
|
|
* Query provides a set of methods to facilitate the specification of different clauses |
19
|
|
|
* in a SELECT statement. These methods can be chained together. |
20
|
|
|
* |
21
|
|
|
* By calling [[createCommand()]], we can get a [[Command]] instance which can be further |
22
|
|
|
* used to perform/execute the DB query against a database. |
23
|
|
|
* |
24
|
|
|
* For example, |
25
|
|
|
* |
26
|
|
|
* ```php |
27
|
|
|
* $query = new Query; |
28
|
|
|
* // compose the query |
29
|
|
|
* $query->select('id, name') |
30
|
|
|
* ->from('user') |
31
|
|
|
* ->limit(10); |
32
|
|
|
* // build and execute the query |
33
|
|
|
* $rows = $query->all(); |
34
|
|
|
* // alternatively, you can create DB command and execute it |
35
|
|
|
* $command = $query->createCommand(); |
36
|
|
|
* // $command->sql returns the actual SQL |
37
|
|
|
* $rows = $command->queryAll(); |
38
|
|
|
* ``` |
39
|
|
|
* |
40
|
|
|
* Query internally uses the [[QueryBuilder]] class to generate the SQL statement. |
41
|
|
|
* |
42
|
|
|
* A more detailed usage guide on how to work with Query can be found in the [guide article on Query Builder](guide:db-query-builder). |
43
|
|
|
* |
44
|
|
|
* @property string[] $tablesUsedInFrom Table names indexed by aliases. This property is read-only. |
45
|
|
|
* |
46
|
|
|
* @author Qiang Xue <[email protected]> |
47
|
|
|
* @author Carsten Brandt <[email protected]> |
48
|
|
|
* @since 2.0 |
49
|
|
|
*/ |
50
|
|
|
class Query extends Component implements QueryInterface |
51
|
|
|
{ |
52
|
|
|
use QueryTrait; |
53
|
|
|
use CacheableQueryTrait; |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @var array the columns being selected. For example, `['id', 'name']`. |
57
|
|
|
* This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns. |
58
|
|
|
* @see select() |
59
|
|
|
*/ |
60
|
|
|
public $select; |
61
|
|
|
/** |
62
|
|
|
* @var string additional option that should be appended to the 'SELECT' keyword. For example, |
63
|
|
|
* in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. |
64
|
|
|
*/ |
65
|
|
|
public $selectOption; |
66
|
|
|
/** |
67
|
|
|
* @var bool whether to select distinct rows of data only. If this is set true, |
68
|
|
|
* the SELECT clause would be changed to SELECT DISTINCT. |
69
|
|
|
*/ |
70
|
|
|
public $distinct; |
71
|
|
|
/** |
72
|
|
|
* @var array the table(s) to be selected from. For example, `['user', 'post']`. |
73
|
|
|
* This is used to construct the FROM clause in a SQL statement. |
74
|
|
|
* @see from() |
75
|
|
|
*/ |
76
|
|
|
public $from; |
77
|
|
|
/** |
78
|
|
|
* @var array how to group the query results. For example, `['company', 'department']`. |
79
|
|
|
* This is used to construct the GROUP BY clause in a SQL statement. |
80
|
|
|
*/ |
81
|
|
|
public $groupBy; |
82
|
|
|
/** |
83
|
|
|
* @var array how to join with other tables. Each array element represents the specification |
84
|
|
|
* of one join which has the following structure: |
85
|
|
|
* |
86
|
|
|
* ```php |
87
|
|
|
* [$joinType, $tableName, $joinCondition] |
88
|
|
|
* ``` |
89
|
|
|
* |
90
|
|
|
* For example, |
91
|
|
|
* |
92
|
|
|
* ```php |
93
|
|
|
* [ |
94
|
|
|
* ['INNER JOIN', 'user', 'user.id = author_id'], |
95
|
|
|
* ['LEFT JOIN', 'team', 'team.id = team_id'], |
96
|
|
|
* ] |
97
|
|
|
* ``` |
98
|
|
|
*/ |
99
|
|
|
public $join; |
100
|
|
|
/** |
101
|
|
|
* @var string|array|ExpressionInterface the condition to be applied in the GROUP BY clause. |
102
|
|
|
* It can be either a string or an array. Please refer to [[where()]] on how to specify the condition. |
103
|
|
|
*/ |
104
|
|
|
public $having; |
105
|
|
|
/** |
106
|
|
|
* @var array this is used to construct the UNION clause(s) in a SQL statement. |
107
|
|
|
* Each array element is an array of the following structure: |
108
|
|
|
* |
109
|
|
|
* - `query`: either a string or a [[Query]] object representing a query |
110
|
|
|
* - `all`: boolean, whether it should be `UNION ALL` or `UNION` |
111
|
|
|
*/ |
112
|
|
|
public $union; |
113
|
|
|
/** |
114
|
|
|
* @var array list of query parameter values indexed by parameter placeholders. |
115
|
|
|
* For example, `[':name' => 'Dan', ':age' => 31]`. |
116
|
|
|
*/ |
117
|
|
|
public $params = []; |
118
|
|
|
|
119
|
|
|
|
120
|
|
|
/** |
121
|
|
|
* Creates a DB command that can be used to execute this query. |
122
|
|
|
* @param Connection $db the database connection used to generate the SQL statement. |
123
|
|
|
* If this parameter is not given, the `db` application component will be used. |
124
|
|
|
* @return Command the created DB command instance. |
125
|
357 |
|
*/ |
126
|
|
|
public function createCommand($db = null) |
127
|
357 |
|
{ |
128
|
31 |
|
if ($db === null) { |
129
|
|
|
$db = Yii::$app->getDb(); |
130
|
357 |
|
} |
131
|
|
|
list($sql, $params) = $db->getQueryBuilder()->build($this); |
132
|
357 |
|
|
133
|
|
|
$command = $db->createCommand($sql, $params); |
134
|
|
|
if ($this->hasCache()) { |
135
|
|
|
$command->cache($this->queryCacheDuration, $this->queryCacheDependency); |
136
|
|
|
} |
137
|
|
|
return $command; |
138
|
|
|
} |
139
|
|
|
|
140
|
|
|
/** |
141
|
|
|
* Prepares for building SQL. |
142
|
742 |
|
* This method is called by [[QueryBuilder]] when it starts to build SQL from a query object. |
143
|
|
|
* You may override this method to do some final preparation work when converting a query into a SQL statement. |
144
|
742 |
|
* @param QueryBuilder $builder |
145
|
|
|
* @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL |
146
|
|
|
*/ |
147
|
|
|
public function prepare($builder) |
|
|
|
|
148
|
|
|
{ |
149
|
|
|
return $this; |
150
|
|
|
} |
151
|
|
|
|
152
|
|
|
/** |
153
|
|
|
* Starts a batch query. |
154
|
|
|
* |
155
|
|
|
* A batch query supports fetching data in batches, which can keep the memory usage under a limit. |
156
|
|
|
* This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface |
157
|
|
|
* and can be traversed to retrieve the data in batches. |
158
|
|
|
* |
159
|
|
|
* For example, |
160
|
|
|
* |
161
|
|
|
* ```php |
162
|
|
|
* $query = (new Query)->from('user'); |
163
|
|
|
* foreach ($query->batch() as $rows) { |
164
|
|
|
* // $rows is an array of 100 or fewer rows from user table |
165
|
|
|
* } |
166
|
|
|
* ``` |
167
|
|
|
* |
168
|
6 |
|
* @param int $batchSize the number of records to be fetched in each batch. |
169
|
|
|
* @param Connection $db the database connection. If not set, the "db" application component will be used. |
170
|
6 |
|
* @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface |
171
|
6 |
|
* and can be traversed to retrieve the data in batches. |
172
|
6 |
|
*/ |
173
|
6 |
|
public function batch($batchSize = 100, $db = null) |
174
|
6 |
|
{ |
175
|
|
|
return Yii::createObject([ |
176
|
|
|
'class' => BatchQueryResult::className(), |
177
|
|
|
'query' => $this, |
178
|
|
|
'batchSize' => $batchSize, |
179
|
|
|
'db' => $db, |
180
|
|
|
'each' => false, |
181
|
|
|
]); |
182
|
|
|
} |
183
|
|
|
|
184
|
|
|
/** |
185
|
|
|
* Starts a batch query and retrieves data row by row. |
186
|
|
|
* |
187
|
|
|
* This method is similar to [[batch()]] except that in each iteration of the result, |
188
|
|
|
* only one row of data is returned. For example, |
189
|
|
|
* |
190
|
|
|
* ```php |
191
|
|
|
* $query = (new Query)->from('user'); |
192
|
|
|
* foreach ($query->each() as $row) { |
193
|
|
|
* } |
194
|
|
|
* ``` |
195
|
|
|
* |
196
|
3 |
|
* @param int $batchSize the number of records to be fetched in each batch. |
197
|
|
|
* @param Connection $db the database connection. If not set, the "db" application component will be used. |
198
|
3 |
|
* @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface |
199
|
3 |
|
* and can be traversed to retrieve the data in batches. |
200
|
3 |
|
*/ |
201
|
3 |
|
public function each($batchSize = 100, $db = null) |
202
|
3 |
|
{ |
203
|
|
|
return Yii::createObject([ |
204
|
|
|
'class' => BatchQueryResult::className(), |
205
|
|
|
'query' => $this, |
206
|
|
|
'batchSize' => $batchSize, |
207
|
|
|
'db' => $db, |
208
|
|
|
'each' => true, |
209
|
|
|
]); |
210
|
|
|
} |
211
|
|
|
|
212
|
|
|
/** |
213
|
412 |
|
* Executes the query and returns all results as an array. |
214
|
|
|
* @param Connection $db the database connection used to generate the SQL statement. |
215
|
412 |
|
* If this parameter is not given, the `db` application component will be used. |
216
|
9 |
|
* @return array the query results. If the query results in nothing, an empty array will be returned. |
217
|
|
|
*/ |
218
|
406 |
|
public function all($db = null) |
219
|
406 |
|
{ |
220
|
|
|
if ($this->emulateExecution) { |
221
|
|
|
return []; |
222
|
|
|
} |
223
|
|
|
$rows = $this->createCommand($db)->queryAll(); |
224
|
|
|
return $this->populate($rows); |
225
|
|
|
} |
226
|
|
|
|
227
|
|
|
/** |
228
|
|
|
* Converts the raw query results into the format as specified by this query. |
229
|
226 |
|
* This method is internally used to convert the data fetched from database |
230
|
|
|
* into the format as required by this query. |
231
|
226 |
|
* @param array $rows the raw query result from database |
232
|
226 |
|
* @return array the converted query result |
233
|
|
|
*/ |
234
|
3 |
|
public function populate($rows) |
235
|
3 |
|
{ |
236
|
3 |
|
if ($this->indexBy === null) { |
237
|
3 |
|
return $rows; |
238
|
|
|
} |
239
|
|
|
$result = []; |
240
|
|
|
foreach ($rows as $row) { |
241
|
3 |
|
if (is_string($this->indexBy)) { |
242
|
|
|
$key = $row[$this->indexBy]; |
243
|
|
|
} else { |
244
|
3 |
|
$key = call_user_func($this->indexBy, $row); |
245
|
|
|
} |
246
|
|
|
$result[$key] = $row; |
247
|
|
|
} |
248
|
|
|
|
249
|
|
|
return $result; |
250
|
|
|
} |
251
|
|
|
|
252
|
|
|
/** |
253
|
|
|
* Executes the query and returns a single row of result. |
254
|
430 |
|
* @param Connection $db the database connection used to generate the SQL statement. |
255
|
|
|
* If this parameter is not given, the `db` application component will be used. |
256
|
430 |
|
* @return array|bool the first row (in terms of an array) of the query result. False is returned if the query |
257
|
6 |
|
* results in nothing. |
258
|
|
|
*/ |
259
|
|
|
public function one($db = null) |
260
|
424 |
|
{ |
261
|
|
|
if ($this->emulateExecution) { |
262
|
|
|
return false; |
263
|
|
|
} |
264
|
|
|
|
265
|
|
|
return $this->createCommand($db)->queryOne(); |
266
|
|
|
} |
267
|
|
|
|
268
|
|
|
/** |
269
|
|
|
* Returns the query result as a scalar value. |
270
|
|
|
* The value returned will be the first column in the first row of the query results. |
271
|
27 |
|
* @param Connection $db the database connection used to generate the SQL statement. |
272
|
|
|
* If this parameter is not given, the `db` application component will be used. |
273
|
27 |
|
* @return string|null|false the value of the first column in the first row of the query result. |
274
|
6 |
|
* False is returned if the query result is empty. |
275
|
|
|
*/ |
276
|
|
|
public function scalar($db = null) |
277
|
21 |
|
{ |
278
|
|
|
if ($this->emulateExecution) { |
279
|
|
|
return null; |
280
|
|
|
} |
281
|
|
|
|
282
|
|
|
return $this->createCommand($db)->queryScalar(); |
283
|
|
|
} |
284
|
|
|
|
285
|
|
|
/** |
286
|
70 |
|
* Executes the query and returns the first column of the result. |
287
|
|
|
* @param Connection $db the database connection used to generate the SQL statement. |
288
|
70 |
|
* If this parameter is not given, the `db` application component will be used. |
289
|
6 |
|
* @return array the first column of the query result. An empty array is returned if the query results in nothing. |
290
|
|
|
*/ |
291
|
|
|
public function column($db = null) |
292
|
64 |
|
{ |
293
|
58 |
|
if ($this->emulateExecution) { |
294
|
|
|
return []; |
295
|
|
|
} |
296
|
9 |
|
|
297
|
9 |
|
if ($this->indexBy === null) { |
298
|
9 |
|
return $this->createCommand($db)->queryColumn(); |
299
|
|
|
} |
300
|
|
|
|
301
|
|
|
if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) { |
302
|
|
|
if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) { |
303
|
9 |
|
$this->select[] = key($tables) . '.' . $this->indexBy; |
304
|
9 |
|
} else { |
305
|
9 |
|
$this->select[] = $this->indexBy; |
306
|
9 |
|
} |
307
|
|
|
} |
308
|
9 |
|
$rows = $this->createCommand($db)->queryAll(); |
309
|
3 |
|
$results = []; |
310
|
|
|
foreach ($rows as $row) { |
311
|
9 |
|
$value = reset($row); |
312
|
|
|
|
313
|
|
|
if ($this->indexBy instanceof \Closure) { |
314
|
|
|
$results[call_user_func($this->indexBy, $row)] = $value; |
315
|
9 |
|
} else { |
316
|
|
|
$results[$row[$this->indexBy]] = $value; |
317
|
|
|
} |
318
|
|
|
} |
319
|
|
|
|
320
|
|
|
return $results; |
321
|
|
|
} |
322
|
|
|
|
323
|
|
|
/** |
324
|
|
|
* Returns the number of records. |
325
|
|
|
* @param string $q the COUNT expression. Defaults to '*'. |
326
|
|
|
* Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
327
|
87 |
|
* @param Connection $db the database connection used to generate the SQL statement. |
328
|
|
|
* If this parameter is not given (or null), the `db` application component will be used. |
329
|
87 |
|
* @return int|string number of records. The result may be a string depending on the |
330
|
6 |
|
* underlying database engine and to support integer values higher than a 32bit PHP integer can handle. |
331
|
|
|
*/ |
332
|
|
|
public function count($q = '*', $db = null) |
333
|
87 |
|
{ |
334
|
|
|
if ($this->emulateExecution) { |
335
|
|
|
return 0; |
336
|
|
|
} |
337
|
|
|
|
338
|
|
|
return $this->queryScalar("COUNT($q)", $db); |
|
|
|
|
339
|
|
|
} |
340
|
|
|
|
341
|
|
|
/** |
342
|
|
|
* Returns the sum of the specified column values. |
343
|
|
|
* @param string $q the column name or expression. |
344
|
9 |
|
* Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
345
|
|
|
* @param Connection $db the database connection used to generate the SQL statement. |
346
|
9 |
|
* If this parameter is not given, the `db` application component will be used. |
347
|
6 |
|
* @return mixed the sum of the specified column values. |
348
|
|
|
*/ |
349
|
|
|
public function sum($q, $db = null) |
350
|
3 |
|
{ |
351
|
|
|
if ($this->emulateExecution) { |
352
|
|
|
return 0; |
353
|
|
|
} |
354
|
|
|
|
355
|
|
|
return $this->queryScalar("SUM($q)", $db); |
356
|
|
|
} |
357
|
|
|
|
358
|
|
|
/** |
359
|
|
|
* Returns the average of the specified column values. |
360
|
|
|
* @param string $q the column name or expression. |
361
|
9 |
|
* Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
362
|
|
|
* @param Connection $db the database connection used to generate the SQL statement. |
363
|
9 |
|
* If this parameter is not given, the `db` application component will be used. |
364
|
6 |
|
* @return mixed the average of the specified column values. |
365
|
|
|
*/ |
366
|
|
|
public function average($q, $db = null) |
367
|
3 |
|
{ |
368
|
|
|
if ($this->emulateExecution) { |
369
|
|
|
return 0; |
370
|
|
|
} |
371
|
|
|
|
372
|
|
|
return $this->queryScalar("AVG($q)", $db); |
373
|
|
|
} |
374
|
|
|
|
375
|
|
|
/** |
376
|
|
|
* Returns the minimum of the specified column values. |
377
|
|
|
* @param string $q the column name or expression. |
378
|
9 |
|
* Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
379
|
|
|
* @param Connection $db the database connection used to generate the SQL statement. |
380
|
9 |
|
* If this parameter is not given, the `db` application component will be used. |
381
|
|
|
* @return mixed the minimum of the specified column values. |
382
|
|
|
*/ |
383
|
|
|
public function min($q, $db = null) |
384
|
|
|
{ |
385
|
|
|
return $this->queryScalar("MIN($q)", $db); |
386
|
|
|
} |
387
|
|
|
|
388
|
|
|
/** |
389
|
|
|
* Returns the maximum of the specified column values. |
390
|
|
|
* @param string $q the column name or expression. |
391
|
9 |
|
* Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression. |
392
|
|
|
* @param Connection $db the database connection used to generate the SQL statement. |
393
|
9 |
|
* If this parameter is not given, the `db` application component will be used. |
394
|
|
|
* @return mixed the maximum of the specified column values. |
395
|
|
|
*/ |
396
|
|
|
public function max($q, $db = null) |
397
|
|
|
{ |
398
|
|
|
return $this->queryScalar("MAX($q)", $db); |
399
|
|
|
} |
400
|
|
|
|
401
|
|
|
/** |
402
|
67 |
|
* Returns a value indicating whether the query result contains any row of data. |
403
|
|
|
* @param Connection $db the database connection used to generate the SQL statement. |
404
|
67 |
|
* If this parameter is not given, the `db` application component will be used. |
405
|
6 |
|
* @return bool whether the query result contains any row of data. |
406
|
|
|
*/ |
407
|
61 |
|
public function exists($db = null) |
408
|
61 |
|
{ |
409
|
61 |
|
if ($this->emulateExecution) { |
410
|
61 |
|
return false; |
411
|
61 |
|
} |
412
|
|
|
$command = $this->createCommand($db); |
413
|
|
|
$params = $command->params; |
414
|
|
|
$command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql())); |
415
|
|
|
$command->bindValues($params); |
416
|
|
|
return (bool) $command->queryScalar(); |
417
|
|
|
} |
418
|
|
|
|
419
|
|
|
/** |
420
|
|
|
* Queries a scalar value by setting [[select]] first. |
421
|
87 |
|
* Restores the value of select to make this query reusable. |
422
|
|
|
* @param string|ExpressionInterface $selectExpression |
423
|
87 |
|
* @param Connection|null $db |
424
|
6 |
|
* @return bool|string |
425
|
|
|
*/ |
426
|
|
|
protected function queryScalar($selectExpression, $db) |
427
|
|
|
{ |
428
|
87 |
|
if ($this->emulateExecution) { |
429
|
87 |
|
return null; |
430
|
87 |
|
} |
431
|
87 |
|
|
432
|
|
|
if ( |
433
|
86 |
|
!$this->distinct |
434
|
86 |
|
&& empty($this->groupBy) |
435
|
86 |
|
&& empty($this->having) |
436
|
86 |
|
&& empty($this->union) |
437
|
|
|
) { |
438
|
86 |
|
$select = $this->select; |
439
|
86 |
|
$order = $this->orderBy; |
440
|
86 |
|
$limit = $this->limit; |
441
|
86 |
|
$offset = $this->offset; |
442
|
86 |
|
|
443
|
|
|
$this->select = [$selectExpression]; |
444
|
86 |
|
$this->orderBy = null; |
|
|
|
|
445
|
86 |
|
$this->limit = null; |
446
|
86 |
|
$this->offset = null; |
447
|
86 |
|
$command = $this->createCommand($db); |
448
|
|
|
|
449
|
86 |
|
$this->select = $select; |
450
|
|
|
$this->orderBy = $order; |
451
|
|
|
$this->limit = $limit; |
452
|
7 |
|
$this->offset = $offset; |
453
|
7 |
|
|
454
|
7 |
|
return $command->queryScalar(); |
455
|
7 |
|
} |
456
|
7 |
|
|
457
|
|
|
$command = (new self()) |
458
|
|
|
->select([$selectExpression]) |
459
|
|
|
->from(['c' => $this]) |
460
|
|
|
->createCommand($db); |
461
|
|
|
if ($this->hasCache()) { |
462
|
|
|
$command->cache($this->queryCacheDuration, $this->queryCacheDependency); |
463
|
|
|
} |
464
|
|
|
return $command->queryScalar(); |
465
|
|
|
} |
466
|
69 |
|
|
467
|
|
|
/** |
468
|
69 |
|
* Returns table names used in [[from]] indexed by aliases. |
469
|
|
|
* Both aliases and names are enclosed into {{ and }}. |
470
|
|
|
* @return string[] table names indexed by aliases |
471
|
|
|
* @throws \yii\base\InvalidConfigException |
472
|
69 |
|
* @since 2.0.12 |
473
|
33 |
|
*/ |
474
|
36 |
|
public function getTablesUsedInFrom() |
475
|
24 |
|
{ |
476
|
12 |
|
if (empty($this->from)) { |
477
|
6 |
|
return []; |
478
|
|
|
} |
479
|
6 |
|
|
480
|
|
|
if (is_array($this->from)) { |
481
|
|
|
$tableNames = $this->from; |
482
|
63 |
|
} elseif (is_string($this->from)) { |
483
|
|
|
$tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY); |
484
|
|
|
} elseif ($this->from instanceof Expression) { |
485
|
|
|
$tableNames = [$this->from]; |
486
|
|
|
} else { |
487
|
|
|
throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.'); |
488
|
|
|
} |
489
|
|
|
|
490
|
|
|
return $this->cleanUpTableNames($tableNames); |
491
|
|
|
} |
492
|
162 |
|
|
493
|
|
|
/** |
494
|
162 |
|
* Clean up table names and aliases |
495
|
162 |
|
* Both aliases and names are enclosed into {{ and }}. |
496
|
162 |
|
* @param array $tableNames non-empty array |
497
|
|
|
* @return string[] table names indexed by aliases |
498
|
141 |
|
* @since 2.0.14 |
499
|
|
|
*/ |
500
|
|
|
protected function cleanUpTableNames($tableNames) |
501
|
|
|
{ |
502
|
|
|
$cleanedUpTableNames = []; |
503
|
|
|
foreach ($tableNames as $alias => $tableName) { |
504
|
|
|
if (is_string($tableName) && !is_string($alias)) { |
505
|
|
|
$pattern = <<<PATTERN |
506
|
|
|
~ |
507
|
|
|
^ |
508
|
|
|
\s* |
509
|
|
|
( |
510
|
|
|
(?:['"`\[]|{{) |
511
|
|
|
.*? |
512
|
|
|
(?:['"`\]]|}}) |
513
|
|
|
| |
514
|
|
|
\(.*?\) |
515
|
|
|
| |
516
|
|
|
.*? |
517
|
|
|
) |
518
|
|
|
(?: |
519
|
|
|
(?: |
520
|
|
|
\s+ |
521
|
|
|
(?:as)? |
522
|
|
|
\s* |
523
|
|
|
) |
524
|
|
|
( |
525
|
|
|
(?:['"`\[]|{{) |
526
|
|
|
.*? |
527
|
|
|
(?:['"`\]]|}}) |
528
|
141 |
|
| |
529
|
141 |
|
.*? |
530
|
18 |
|
) |
531
|
|
|
)? |
532
|
135 |
|
\s* |
533
|
|
|
$ |
534
|
|
|
~iux |
535
|
|
|
PATTERN; |
536
|
|
|
if (preg_match($pattern, $tableName, $matches)) { |
537
|
|
|
if (isset($matches[2])) { |
538
|
162 |
|
list(, $tableName, $alias) = $matches; |
539
|
12 |
|
} else { |
540
|
6 |
|
$tableName = $alias = $matches[1]; |
541
|
|
|
} |
542
|
6 |
|
} |
543
|
150 |
|
} |
544
|
6 |
|
|
545
|
|
|
|
546
|
156 |
|
if ($tableName instanceof Expression) { |
547
|
|
|
if (!is_string($alias)) { |
548
|
|
|
throw new InvalidParamException('To use Expression in from() method, pass it in array format with alias.'); |
549
|
|
|
} |
550
|
156 |
|
$cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName; |
551
|
|
|
} elseif ($tableName instanceof self) { |
552
|
|
|
$cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName; |
553
|
|
|
} else { |
554
|
|
|
$cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName); |
555
|
|
|
} |
556
|
|
|
} |
557
|
|
|
|
558
|
156 |
|
return $cleanedUpTableNames; |
559
|
|
|
} |
560
|
156 |
|
|
561
|
156 |
|
/** |
562
|
144 |
|
* Ensures name is wrapped with {{ and }} |
563
|
|
|
* @param string $name |
564
|
|
|
* @return string |
565
|
30 |
|
*/ |
566
|
|
|
private function ensureNameQuoted($name) |
567
|
|
|
{ |
568
|
|
|
$name = str_replace(["'", '"', '`', '[', ']'], '', $name); |
569
|
|
|
if ($name && !preg_match('/^{{.*}}$/', $name)) { |
570
|
|
|
return '{{' . $name . '}}'; |
571
|
|
|
} |
572
|
|
|
|
573
|
|
|
return $name; |
574
|
|
|
} |
575
|
|
|
|
576
|
|
|
/** |
577
|
|
|
* Sets the SELECT part of the query. |
578
|
|
|
* @param string|array|ExpressionInterface $columns the columns to be selected. |
579
|
|
|
* Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). |
580
|
|
|
* Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id"). |
581
|
|
|
* The method will automatically quote the column names unless a column contains some parenthesis |
582
|
|
|
* (which means the column contains a DB expression). A DB expression may also be passed in form of |
583
|
|
|
* an [[ExpressionInterface]] object. |
584
|
|
|
* |
585
|
|
|
* Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should |
586
|
|
|
* use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts. |
587
|
|
|
* |
588
|
|
|
* When the columns are specified as an array, you may also use array keys as the column aliases (if a column |
589
|
|
|
* does not need alias, do not use a string key). |
590
|
390 |
|
* |
591
|
|
|
* Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column |
592
|
390 |
|
* as a `Query` instance representing the sub-query. |
593
|
3 |
|
* |
594
|
387 |
|
* @param string $option additional option that should be appended to the 'SELECT' keyword. For example, |
595
|
107 |
|
* in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used. |
596
|
|
|
* @return $this the query object itself |
597
|
390 |
|
*/ |
598
|
390 |
|
public function select($columns, $option = null) |
599
|
390 |
|
{ |
600
|
|
|
if ($columns instanceof ExpressionInterface) { |
601
|
|
|
$columns = [$columns]; |
602
|
|
|
} elseif (!is_array($columns)) { |
603
|
|
|
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); |
604
|
|
|
} |
605
|
|
|
$this->select = $this->getUniqueColumns($columns); |
606
|
|
|
$this->selectOption = $option; |
607
|
|
|
return $this; |
608
|
|
|
} |
609
|
|
|
|
610
|
|
|
/** |
611
|
|
|
* Add more columns to the SELECT part of the query. |
612
|
|
|
* |
613
|
|
|
* Note, that if [[select]] has not been specified before, you should include `*` explicitly |
614
|
|
|
* if you want to select all remaining columns too: |
615
|
|
|
* |
616
|
|
|
* ```php |
617
|
9 |
|
* $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one(); |
618
|
|
|
* ``` |
619
|
9 |
|
* |
620
|
3 |
|
* @param string|array|ExpressionInterface $columns the columns to add to the select. See [[select()]] for more |
621
|
9 |
|
* details about the format of this parameter. |
622
|
3 |
|
* @return $this the query object itself |
623
|
|
|
* @see select() |
624
|
9 |
|
*/ |
625
|
9 |
|
public function addSelect($columns) |
626
|
3 |
|
{ |
627
|
|
|
if ($columns instanceof ExpressionInterface) { |
628
|
9 |
|
$columns = [$columns]; |
629
|
|
|
} elseif (!is_array($columns)) { |
630
|
|
|
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); |
631
|
9 |
|
} |
632
|
|
|
$columns = $this->getUniqueColumns($columns); |
633
|
|
|
if ($this->select === null) { |
634
|
|
|
$this->select = $columns; |
635
|
|
|
} else { |
636
|
|
|
$this->select = array_merge($this->select, $columns); |
637
|
|
|
} |
638
|
|
|
|
639
|
|
|
return $this; |
640
|
|
|
} |
641
|
|
|
|
642
|
390 |
|
/** |
643
|
|
|
* Returns unique column names excluding duplicates. |
644
|
390 |
|
* Columns to be removed: |
645
|
390 |
|
* - if column definition already present in SELECT part with same alias |
646
|
|
|
* - if column definition without alias already present in SELECT part without alias too |
647
|
390 |
|
* @param array $columns the columns to be merged to the select. |
648
|
387 |
|
* @since 2.0.14 |
649
|
3 |
|
*/ |
650
|
|
|
protected function getUniqueColumns($columns) |
651
|
|
|
{ |
652
|
|
|
$columns = array_unique($columns); |
653
|
387 |
|
$unaliasedColumns = $this->getUnaliasedColumnsFromSelect(); |
654
|
387 |
|
|
655
|
|
|
foreach ($columns as $columnAlias => $columnDefinition) { |
656
|
387 |
|
if ($columnDefinition instanceof Query) { |
657
|
|
|
continue; |
658
|
|
|
} |
659
|
390 |
|
|
660
|
|
|
if ( |
661
|
|
|
(is_string($columnAlias) && isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition) |
662
|
|
|
|| (is_integer($columnAlias) && in_array($columnDefinition, $unaliasedColumns)) |
663
|
|
|
) { |
664
|
|
|
unset($columns[$columnAlias]); |
665
|
|
|
} |
666
|
390 |
|
} |
667
|
|
|
return $columns; |
668
|
390 |
|
} |
669
|
390 |
|
|
670
|
9 |
|
/** |
671
|
9 |
|
* @return array List of columns without aliases from SELECT statement. |
672
|
9 |
|
* @since 2.0.14 |
673
|
|
|
*/ |
674
|
|
|
protected function getUnaliasedColumnsFromSelect() |
675
|
|
|
{ |
676
|
390 |
|
$result = []; |
677
|
|
|
if (is_array($this->select)) { |
678
|
|
|
foreach ($this->select as $name => $value) { |
679
|
|
|
if (is_integer($name)) { |
680
|
|
|
$result[] = $value; |
681
|
|
|
} |
682
|
|
|
} |
683
|
|
|
} |
684
|
6 |
|
return array_unique($result); |
685
|
|
|
} |
686
|
6 |
|
|
687
|
6 |
|
/** |
688
|
|
|
* Sets the value indicating whether to SELECT DISTINCT or not. |
689
|
|
|
* @param bool $value whether to SELECT DISTINCT or not. |
690
|
|
|
* @return $this the query object itself |
691
|
|
|
*/ |
692
|
|
|
public function distinct($value = true) |
693
|
|
|
{ |
694
|
|
|
$this->distinct = $value; |
695
|
|
|
return $this; |
696
|
|
|
} |
697
|
|
|
|
698
|
|
|
/** |
699
|
|
|
* Sets the FROM part of the query. |
700
|
|
|
* @param string|array|ExpressionInterface $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`) |
701
|
|
|
* or an array (e.g. `['user', 'profile']`) specifying one or several table names. |
702
|
|
|
* Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`). |
703
|
|
|
* The method will automatically quote the table names unless it contains some parenthesis |
704
|
|
|
* (which means the table is given as a sub-query or DB expression). |
705
|
|
|
* |
706
|
|
|
* When the tables are specified as an array, you may also use the array keys as the table aliases |
707
|
|
|
* (if a table does not need alias, do not use a string key). |
708
|
|
|
* |
709
|
|
|
* Use a Query object to represent a sub-query. In this case, the corresponding array key will be used |
710
|
|
|
* as the alias for the sub-query. |
711
|
|
|
* |
712
|
|
|
* To specify the `FROM` part in plain SQL, you may pass an instance of [[ExpressionInterface]]. |
713
|
|
|
* |
714
|
|
|
* Here are some examples: |
715
|
|
|
* |
716
|
|
|
* ```php |
717
|
|
|
* // SELECT * FROM `user` `u`, `profile`; |
718
|
|
|
* $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']); |
719
|
|
|
* |
720
|
|
|
* // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; |
721
|
|
|
* $subquery = (new \yii\db\Query)->from('user')->where(['active' => true]) |
722
|
|
|
* $query = (new \yii\db\Query)->from(['activeusers' => $subquery]); |
723
|
|
|
* |
724
|
429 |
|
* // subquery can also be a string with plain SQL wrapped in parenthesis |
725
|
|
|
* // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`; |
726
|
429 |
|
* $subquery = "(SELECT * FROM `user` WHERE `active` = 1)"; |
727
|
6 |
|
* $query = (new \yii\db\Query)->from(['activeusers' => $subquery]); |
728
|
|
|
* ``` |
729
|
429 |
|
* |
730
|
393 |
|
* @return $this the query object itself |
731
|
|
|
*/ |
732
|
429 |
|
public function from($tables) |
733
|
429 |
|
{ |
734
|
|
|
if ($tables instanceof Expression) { |
735
|
|
|
$tables = [$tables]; |
736
|
|
|
} |
737
|
|
|
if (is_string($tables)) { |
738
|
|
|
$tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY); |
739
|
|
|
} |
740
|
|
|
$this->from = $tables; |
|
|
|
|
741
|
|
|
return $this; |
742
|
|
|
} |
743
|
|
|
|
744
|
|
|
/** |
745
|
|
|
* Sets the WHERE part of the query. |
746
|
|
|
* |
747
|
|
|
* The method requires a `$condition` parameter, and optionally a `$params` parameter |
748
|
|
|
* specifying the values to be bound to the query. |
749
|
|
|
* |
750
|
|
|
* The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array. |
751
|
|
|
* |
752
|
|
|
* {@inheritdoc} |
753
|
717 |
|
* |
754
|
|
|
* @param string|array|ExpressionInterface $condition the conditions that should be put in the WHERE part. |
755
|
717 |
|
* @param array $params the parameters (name => value) to be bound to the query. |
756
|
717 |
|
* @return $this the query object itself |
757
|
717 |
|
* @see andWhere() |
758
|
|
|
* @see orWhere() |
759
|
|
|
* @see QueryInterface::where() |
760
|
|
|
*/ |
761
|
|
|
public function where($condition, $params = []) |
762
|
|
|
{ |
763
|
|
|
$this->where = $condition; |
|
|
|
|
764
|
|
|
$this->addParams($params); |
765
|
|
|
return $this; |
766
|
|
|
} |
767
|
|
|
|
768
|
|
|
/** |
769
|
|
|
* Adds an additional WHERE condition to the existing one. |
770
|
314 |
|
* The new condition and the existing one will be joined using the `AND` operator. |
771
|
|
|
* @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]] |
772
|
314 |
|
* on how to specify this parameter. |
773
|
262 |
|
* @param array $params the parameters (name => value) to be bound to the query. |
774
|
100 |
|
* @return $this the query object itself |
775
|
38 |
|
* @see where() |
776
|
|
|
* @see orWhere() |
777
|
100 |
|
*/ |
778
|
|
|
public function andWhere($condition, $params = []) |
779
|
314 |
|
{ |
780
|
314 |
|
if ($this->where === null) { |
781
|
|
|
$this->where = $condition; |
|
|
|
|
782
|
|
|
} elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) { |
783
|
|
|
$this->where[] = $condition; |
784
|
|
|
} else { |
785
|
|
|
$this->where = ['and', $this->where, $condition]; |
786
|
|
|
} |
787
|
|
|
$this->addParams($params); |
788
|
|
|
return $this; |
789
|
|
|
} |
790
|
|
|
|
791
|
|
|
/** |
792
|
|
|
* Adds an additional WHERE condition to the existing one. |
793
|
7 |
|
* The new condition and the existing one will be joined using the `OR` operator. |
794
|
|
|
* @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]] |
795
|
7 |
|
* on how to specify this parameter. |
796
|
|
|
* @param array $params the parameters (name => value) to be bound to the query. |
797
|
|
|
* @return $this the query object itself |
798
|
7 |
|
* @see where() |
799
|
|
|
* @see andWhere() |
800
|
7 |
|
*/ |
801
|
7 |
|
public function orWhere($condition, $params = []) |
802
|
|
|
{ |
803
|
|
|
if ($this->where === null) { |
804
|
|
|
$this->where = $condition; |
|
|
|
|
805
|
|
|
} else { |
806
|
|
|
$this->where = ['or', $this->where, $condition]; |
807
|
|
|
} |
808
|
|
|
$this->addParams($params); |
809
|
|
|
return $this; |
810
|
|
|
} |
811
|
|
|
|
812
|
|
|
/** |
813
|
|
|
* Adds a filtering condition for a specific column and allow the user to choose a filter operator. |
814
|
|
|
* |
815
|
|
|
* It adds an additional WHERE condition for the given field and determines the comparison operator |
816
|
|
|
* based on the first few characters of the given value. |
817
|
|
|
* The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored. |
818
|
|
|
* The new condition and the existing one will be joined using the `AND` operator. |
819
|
|
|
* |
820
|
|
|
* The comparison operator is intelligently determined based on the first few characters in the given value. |
821
|
|
|
* In particular, it recognizes the following operators if they appear as the leading characters in the given value: |
822
|
|
|
* |
823
|
|
|
* - `<`: the column must be less than the given value. |
824
|
|
|
* - `>`: the column must be greater than the given value. |
825
|
|
|
* - `<=`: the column must be less than or equal to the given value. |
826
|
|
|
* - `>=`: the column must be greater than or equal to the given value. |
827
|
|
|
* - `<>`: the column must not be the same as the given value. |
828
|
|
|
* - `=`: the column must be equal to the given value. |
829
|
|
|
* - If none of the above operators is detected, the `$defaultOperator` will be used. |
830
|
3 |
|
* |
831
|
|
|
* @param string $name the column name. |
832
|
3 |
|
* @param string $value the column value optionally prepended with the comparison operator. |
833
|
3 |
|
* @param string $defaultOperator The operator to use, when no operator is given in `$value`. |
834
|
3 |
|
* Defaults to `=`, performing an exact match. |
835
|
|
|
* @return $this The query object itself |
836
|
3 |
|
* @since 2.0.8 |
837
|
|
|
*/ |
838
|
|
|
public function andFilterCompare($name, $value, $defaultOperator = '=') |
839
|
3 |
|
{ |
840
|
|
|
if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) { |
841
|
|
|
$operator = $matches[1]; |
842
|
|
|
$value = substr($value, strlen($operator)); |
843
|
|
|
} else { |
844
|
|
|
$operator = $defaultOperator; |
845
|
|
|
} |
846
|
|
|
|
847
|
|
|
return $this->andFilterWhere([$operator, $name, $value]); |
848
|
|
|
} |
849
|
|
|
|
850
|
|
|
/** |
851
|
|
|
* Appends a JOIN part to the query. |
852
|
|
|
* The first parameter specifies what type of join it is. |
853
|
|
|
* @param string $type the type of join, such as INNER JOIN, LEFT JOIN. |
854
|
|
|
* @param string|array $table the table to be joined. |
855
|
|
|
* |
856
|
|
|
* Use a string to represent the name of the table to be joined. |
857
|
|
|
* The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). |
858
|
|
|
* The method will automatically quote the table name unless it contains some parenthesis |
859
|
|
|
* (which means the table is given as a sub-query or DB expression). |
860
|
|
|
* |
861
|
|
|
* Use an array to represent joining with a sub-query. The array must contain only one element. |
862
|
|
|
* The value must be a [[Query]] object representing the sub-query while the corresponding key |
863
|
|
|
* represents the alias for the sub-query. |
864
|
|
|
* |
865
|
|
|
* @param string|array $on the join condition that should appear in the ON part. |
866
|
|
|
* Please refer to [[where()]] on how to specify this parameter. |
867
|
|
|
* |
868
|
|
|
* Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so |
869
|
|
|
* the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would |
870
|
|
|
* match the `post.author_id` column value against the string `'user.id'`. |
871
|
|
|
* It is recommended to use the string syntax here which is more suited for a join: |
872
|
48 |
|
* |
873
|
|
|
* ```php |
874
|
48 |
|
* 'post.author_id = user.id' |
875
|
48 |
|
* ``` |
876
|
|
|
* |
877
|
|
|
* @param array $params the parameters (name => value) to be bound to the query. |
878
|
|
|
* @return $this the query object itself |
879
|
|
|
*/ |
880
|
|
|
public function join($type, $table, $on = '', $params = []) |
881
|
|
|
{ |
882
|
|
|
$this->join[] = [$type, $table, $on]; |
883
|
|
|
return $this->addParams($params); |
884
|
|
|
} |
885
|
|
|
|
886
|
|
|
/** |
887
|
|
|
* Appends an INNER JOIN part to the query. |
888
|
|
|
* @param string|array $table the table to be joined. |
889
|
|
|
* |
890
|
|
|
* Use a string to represent the name of the table to be joined. |
891
|
|
|
* The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). |
892
|
|
|
* The method will automatically quote the table name unless it contains some parenthesis |
893
|
|
|
* (which means the table is given as a sub-query or DB expression). |
894
|
|
|
* |
895
|
|
|
* Use an array to represent joining with a sub-query. The array must contain only one element. |
896
|
3 |
|
* The value must be a [[Query]] object representing the sub-query while the corresponding key |
897
|
|
|
* represents the alias for the sub-query. |
898
|
3 |
|
* |
899
|
3 |
|
* @param string|array $on the join condition that should appear in the ON part. |
900
|
|
|
* Please refer to [[join()]] on how to specify this parameter. |
901
|
|
|
* @param array $params the parameters (name => value) to be bound to the query. |
902
|
|
|
* @return $this the query object itself |
903
|
|
|
*/ |
904
|
|
|
public function innerJoin($table, $on = '', $params = []) |
905
|
|
|
{ |
906
|
|
|
$this->join[] = ['INNER JOIN', $table, $on]; |
907
|
|
|
return $this->addParams($params); |
908
|
|
|
} |
909
|
|
|
|
910
|
|
|
/** |
911
|
|
|
* Appends a LEFT OUTER JOIN part to the query. |
912
|
|
|
* @param string|array $table the table to be joined. |
913
|
|
|
* |
914
|
|
|
* Use a string to represent the name of the table to be joined. |
915
|
|
|
* The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). |
916
|
|
|
* The method will automatically quote the table name unless it contains some parenthesis |
917
|
|
|
* (which means the table is given as a sub-query or DB expression). |
918
|
|
|
* |
919
|
|
|
* Use an array to represent joining with a sub-query. The array must contain only one element. |
920
|
3 |
|
* The value must be a [[Query]] object representing the sub-query while the corresponding key |
921
|
|
|
* represents the alias for the sub-query. |
922
|
3 |
|
* |
923
|
3 |
|
* @param string|array $on the join condition that should appear in the ON part. |
924
|
|
|
* Please refer to [[join()]] on how to specify this parameter. |
925
|
|
|
* @param array $params the parameters (name => value) to be bound to the query |
926
|
|
|
* @return $this the query object itself |
927
|
|
|
*/ |
928
|
|
|
public function leftJoin($table, $on = '', $params = []) |
929
|
|
|
{ |
930
|
|
|
$this->join[] = ['LEFT JOIN', $table, $on]; |
931
|
|
|
return $this->addParams($params); |
932
|
|
|
} |
933
|
|
|
|
934
|
|
|
/** |
935
|
|
|
* Appends a RIGHT OUTER JOIN part to the query. |
936
|
|
|
* @param string|array $table the table to be joined. |
937
|
|
|
* |
938
|
|
|
* Use a string to represent the name of the table to be joined. |
939
|
|
|
* The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u'). |
940
|
|
|
* The method will automatically quote the table name unless it contains some parenthesis |
941
|
|
|
* (which means the table is given as a sub-query or DB expression). |
942
|
|
|
* |
943
|
|
|
* Use an array to represent joining with a sub-query. The array must contain only one element. |
944
|
|
|
* The value must be a [[Query]] object representing the sub-query while the corresponding key |
945
|
|
|
* represents the alias for the sub-query. |
946
|
|
|
* |
947
|
|
|
* @param string|array $on the join condition that should appear in the ON part. |
948
|
|
|
* Please refer to [[join()]] on how to specify this parameter. |
949
|
|
|
* @param array $params the parameters (name => value) to be bound to the query |
950
|
|
|
* @return $this the query object itself |
951
|
|
|
*/ |
952
|
|
|
public function rightJoin($table, $on = '', $params = []) |
953
|
|
|
{ |
954
|
|
|
$this->join[] = ['RIGHT JOIN', $table, $on]; |
955
|
|
|
return $this->addParams($params); |
956
|
|
|
} |
957
|
|
|
|
958
|
|
|
/** |
959
|
|
|
* Sets the GROUP BY part of the query. |
960
|
|
|
* @param string|array|ExpressionInterface $columns the columns to be grouped by. |
961
|
|
|
* Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). |
962
|
|
|
* The method will automatically quote the column names unless a column contains some parenthesis |
963
|
|
|
* (which means the column contains a DB expression). |
964
|
|
|
* |
965
|
|
|
* Note that if your group-by is an expression containing commas, you should always use an array |
966
|
24 |
|
* to represent the group-by information. Otherwise, the method will not be able to correctly determine |
967
|
|
|
* the group-by columns. |
968
|
24 |
|
* |
969
|
3 |
|
* Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL. |
970
|
24 |
|
* Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well. |
971
|
24 |
|
* @return $this the query object itself |
972
|
|
|
* @see addGroupBy() |
973
|
24 |
|
*/ |
974
|
24 |
|
public function groupBy($columns) |
975
|
|
|
{ |
976
|
|
|
if ($columns instanceof ExpressionInterface) { |
977
|
|
|
$columns = [$columns]; |
978
|
|
|
} elseif (!is_array($columns)) { |
979
|
|
|
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); |
980
|
|
|
} |
981
|
|
|
$this->groupBy = $columns; |
982
|
|
|
return $this; |
983
|
|
|
} |
984
|
|
|
|
985
|
|
|
/** |
986
|
|
|
* Adds additional group-by columns to the existing ones. |
987
|
|
|
* @param string|array $columns additional columns to be grouped by. |
988
|
|
|
* Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']). |
989
|
|
|
* The method will automatically quote the column names unless a column contains some parenthesis |
990
|
|
|
* (which means the column contains a DB expression). |
991
|
|
|
* |
992
|
|
|
* Note that if your group-by is an expression containing commas, you should always use an array |
993
|
3 |
|
* to represent the group-by information. Otherwise, the method will not be able to correctly determine |
994
|
|
|
* the group-by columns. |
995
|
3 |
|
* |
996
|
|
|
* Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL. |
997
|
3 |
|
* Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well. |
998
|
3 |
|
* @return $this the query object itself |
999
|
|
|
* @see groupBy() |
1000
|
3 |
|
*/ |
1001
|
|
|
public function addGroupBy($columns) |
1002
|
|
|
{ |
1003
|
3 |
|
if ($columns instanceof ExpressionInterface) { |
1004
|
|
|
$columns = [$columns]; |
1005
|
|
|
} elseif (!is_array($columns)) { |
1006
|
3 |
|
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY); |
1007
|
|
|
} |
1008
|
|
|
if ($this->groupBy === null) { |
1009
|
|
|
$this->groupBy = $columns; |
1010
|
|
|
} else { |
1011
|
|
|
$this->groupBy = array_merge($this->groupBy, $columns); |
1012
|
|
|
} |
1013
|
|
|
|
1014
|
|
|
return $this; |
1015
|
|
|
} |
1016
|
|
|
|
1017
|
|
|
/** |
1018
|
10 |
|
* Sets the HAVING part of the query. |
1019
|
|
|
* @param string|array|ExpressionInterface $condition the conditions to be put after HAVING. |
1020
|
10 |
|
* Please refer to [[where()]] on how to specify this parameter. |
1021
|
10 |
|
* @param array $params the parameters (name => value) to be bound to the query. |
1022
|
10 |
|
* @return $this the query object itself |
1023
|
|
|
* @see andHaving() |
1024
|
|
|
* @see orHaving() |
1025
|
|
|
*/ |
1026
|
|
|
public function having($condition, $params = []) |
1027
|
|
|
{ |
1028
|
|
|
$this->having = $condition; |
1029
|
|
|
$this->addParams($params); |
1030
|
|
|
return $this; |
1031
|
|
|
} |
1032
|
|
|
|
1033
|
|
|
/** |
1034
|
|
|
* Adds an additional HAVING condition to the existing one. |
1035
|
3 |
|
* The new condition and the existing one will be joined using the `AND` operator. |
1036
|
|
|
* @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]] |
1037
|
3 |
|
* on how to specify this parameter. |
1038
|
|
|
* @param array $params the parameters (name => value) to be bound to the query. |
1039
|
|
|
* @return $this the query object itself |
1040
|
3 |
|
* @see having() |
1041
|
|
|
* @see orHaving() |
1042
|
3 |
|
*/ |
1043
|
3 |
|
public function andHaving($condition, $params = []) |
1044
|
|
|
{ |
1045
|
|
|
if ($this->having === null) { |
1046
|
|
|
$this->having = $condition; |
1047
|
|
|
} else { |
1048
|
|
|
$this->having = ['and', $this->having, $condition]; |
1049
|
|
|
} |
1050
|
|
|
$this->addParams($params); |
1051
|
|
|
return $this; |
1052
|
|
|
} |
1053
|
|
|
|
1054
|
|
|
/** |
1055
|
|
|
* Adds an additional HAVING condition to the existing one. |
1056
|
3 |
|
* The new condition and the existing one will be joined using the `OR` operator. |
1057
|
|
|
* @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]] |
1058
|
3 |
|
* on how to specify this parameter. |
1059
|
|
|
* @param array $params the parameters (name => value) to be bound to the query. |
1060
|
|
|
* @return $this the query object itself |
1061
|
3 |
|
* @see having() |
1062
|
|
|
* @see andHaving() |
1063
|
3 |
|
*/ |
1064
|
3 |
|
public function orHaving($condition, $params = []) |
1065
|
|
|
{ |
1066
|
|
|
if ($this->having === null) { |
1067
|
|
|
$this->having = $condition; |
1068
|
|
|
} else { |
1069
|
|
|
$this->having = ['or', $this->having, $condition]; |
1070
|
|
|
} |
1071
|
|
|
$this->addParams($params); |
1072
|
|
|
return $this; |
1073
|
|
|
} |
1074
|
|
|
|
1075
|
|
|
/** |
1076
|
|
|
* Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]]. |
1077
|
|
|
* |
1078
|
|
|
* This method is similar to [[having()]]. The main difference is that this method will |
1079
|
|
|
* remove [[isEmpty()|empty query operands]]. As a result, this method is best suited |
1080
|
|
|
* for building query conditions based on filter values entered by users. |
1081
|
|
|
* |
1082
|
|
|
* The following code shows the difference between this method and [[having()]]: |
1083
|
|
|
* |
1084
|
|
|
* ```php |
1085
|
|
|
* // HAVING `age`=:age |
1086
|
|
|
* $query->filterHaving(['name' => null, 'age' => 20]); |
1087
|
|
|
* // HAVING `age`=:age |
1088
|
|
|
* $query->having(['age' => 20]); |
1089
|
|
|
* // HAVING `name` IS NULL AND `age`=:age |
1090
|
|
|
* $query->having(['name' => null, 'age' => 20]); |
1091
|
|
|
* ``` |
1092
|
|
|
* |
1093
|
|
|
* Note that unlike [[having()]], you cannot pass binding parameters to this method. |
1094
|
|
|
* |
1095
|
6 |
|
* @param array $condition the conditions that should be put in the HAVING part. |
1096
|
|
|
* See [[having()]] on how to specify this parameter. |
1097
|
6 |
|
* @return $this the query object itself |
1098
|
6 |
|
* @see having() |
1099
|
6 |
|
* @see andFilterHaving() |
1100
|
|
|
* @see orFilterHaving() |
1101
|
|
|
* @since 2.0.11 |
1102
|
6 |
|
*/ |
1103
|
|
|
public function filterHaving(array $condition) |
1104
|
|
|
{ |
1105
|
|
|
$condition = $this->filterCondition($condition); |
1106
|
|
|
if ($condition !== []) { |
1107
|
|
|
$this->having($condition); |
1108
|
|
|
} |
1109
|
|
|
|
1110
|
|
|
return $this; |
1111
|
|
|
} |
1112
|
|
|
|
1113
|
|
|
/** |
1114
|
|
|
* Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]]. |
1115
|
|
|
* The new condition and the existing one will be joined using the `AND` operator. |
1116
|
|
|
* |
1117
|
|
|
* This method is similar to [[andHaving()]]. The main difference is that this method will |
1118
|
|
|
* remove [[isEmpty()|empty query operands]]. As a result, this method is best suited |
1119
|
|
|
* for building query conditions based on filter values entered by users. |
1120
|
6 |
|
* |
1121
|
|
|
* @param array $condition the new HAVING condition. Please refer to [[having()]] |
1122
|
6 |
|
* on how to specify this parameter. |
1123
|
6 |
|
* @return $this the query object itself |
1124
|
|
|
* @see filterHaving() |
1125
|
|
|
* @see orFilterHaving() |
1126
|
|
|
* @since 2.0.11 |
1127
|
6 |
|
*/ |
1128
|
|
|
public function andFilterHaving(array $condition) |
1129
|
|
|
{ |
1130
|
|
|
$condition = $this->filterCondition($condition); |
1131
|
|
|
if ($condition !== []) { |
1132
|
|
|
$this->andHaving($condition); |
1133
|
|
|
} |
1134
|
|
|
|
1135
|
|
|
return $this; |
1136
|
|
|
} |
1137
|
|
|
|
1138
|
|
|
/** |
1139
|
|
|
* Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]]. |
1140
|
|
|
* The new condition and the existing one will be joined using the `OR` operator. |
1141
|
|
|
* |
1142
|
|
|
* This method is similar to [[orHaving()]]. The main difference is that this method will |
1143
|
|
|
* remove [[isEmpty()|empty query operands]]. As a result, this method is best suited |
1144
|
|
|
* for building query conditions based on filter values entered by users. |
1145
|
6 |
|
* |
1146
|
|
|
* @param array $condition the new HAVING condition. Please refer to [[having()]] |
1147
|
6 |
|
* on how to specify this parameter. |
1148
|
6 |
|
* @return $this the query object itself |
1149
|
|
|
* @see filterHaving() |
1150
|
|
|
* @see andFilterHaving() |
1151
|
|
|
* @since 2.0.11 |
1152
|
6 |
|
*/ |
1153
|
|
|
public function orFilterHaving(array $condition) |
1154
|
|
|
{ |
1155
|
|
|
$condition = $this->filterCondition($condition); |
1156
|
|
|
if ($condition !== []) { |
1157
|
|
|
$this->orHaving($condition); |
1158
|
|
|
} |
1159
|
|
|
|
1160
|
|
|
return $this; |
1161
|
10 |
|
} |
1162
|
|
|
|
1163
|
10 |
|
/** |
1164
|
10 |
|
* Appends a SQL statement using UNION operator. |
1165
|
|
|
* @param string|Query $sql the SQL statement to be appended using UNION |
1166
|
|
|
* @param bool $all TRUE if using UNION ALL and FALSE if using UNION |
1167
|
|
|
* @return $this the query object itself |
1168
|
|
|
*/ |
1169
|
|
|
public function union($sql, $all = false) |
1170
|
|
|
{ |
1171
|
|
|
$this->union[] = ['query' => $sql, 'all' => $all]; |
1172
|
|
|
return $this; |
1173
|
|
|
} |
1174
|
6 |
|
|
1175
|
|
|
/** |
1176
|
6 |
|
* Sets the parameters to be bound to the query. |
1177
|
6 |
|
* @param array $params list of query parameter values indexed by parameter placeholders. |
1178
|
|
|
* For example, `[':name' => 'Dan', ':age' => 31]`. |
1179
|
|
|
* @return $this the query object itself |
1180
|
|
|
* @see addParams() |
1181
|
|
|
*/ |
1182
|
|
|
public function params($params) |
1183
|
|
|
{ |
1184
|
|
|
$this->params = $params; |
1185
|
|
|
return $this; |
1186
|
|
|
} |
1187
|
947 |
|
|
1188
|
|
|
/** |
1189
|
947 |
|
* Adds additional parameters to be bound to the query. |
1190
|
74 |
|
* @param array $params list of query parameter values indexed by parameter placeholders. |
1191
|
74 |
|
* For example, `[':name' => 'Dan', ':age' => 31]`. |
1192
|
|
|
* @return $this the query object itself |
1193
|
6 |
|
* @see params() |
1194
|
6 |
|
*/ |
1195
|
|
|
public function addParams($params) |
1196
|
|
|
{ |
1197
|
6 |
|
if (!empty($params)) { |
1198
|
|
|
if (empty($this->params)) { |
1199
|
|
|
$this->params = $params; |
1200
|
|
|
} else { |
1201
|
|
|
foreach ($params as $name => $value) { |
1202
|
|
|
if (is_int($name)) { |
1203
|
947 |
|
$this->params[] = $value; |
1204
|
|
|
} else { |
1205
|
|
|
$this->params[$name] = $value; |
1206
|
|
|
} |
1207
|
|
|
} |
1208
|
|
|
} |
1209
|
|
|
} |
1210
|
|
|
|
1211
|
|
|
return $this; |
1212
|
360 |
|
} |
1213
|
|
|
|
1214
|
360 |
|
/** |
1215
|
360 |
|
* Creates a new Query object and copies its property values from an existing one. |
1216
|
360 |
|
* The properties being copies are the ones to be used by query builders. |
1217
|
360 |
|
* @param Query $from the source query object |
1218
|
360 |
|
* @return Query the new Query object |
1219
|
360 |
|
*/ |
1220
|
360 |
|
public static function create($from) |
1221
|
360 |
|
{ |
1222
|
360 |
|
return new self([ |
1223
|
360 |
|
'where' => $from->where, |
1224
|
360 |
|
'limit' => $from->limit, |
1225
|
360 |
|
'offset' => $from->offset, |
1226
|
360 |
|
'orderBy' => $from->orderBy, |
1227
|
360 |
|
'indexBy' => $from->indexBy, |
1228
|
360 |
|
'select' => $from->select, |
1229
|
|
|
'selectOption' => $from->selectOption, |
1230
|
|
|
'distinct' => $from->distinct, |
1231
|
|
|
'from' => $from->from, |
1232
|
|
|
'groupBy' => $from->groupBy, |
1233
|
|
|
'join' => $from->join, |
1234
|
|
|
'having' => $from->having, |
1235
|
|
|
'union' => $from->union, |
1236
|
|
|
'params' => $from->params, |
1237
|
|
|
]); |
1238
|
|
|
} |
1239
|
|
|
|
1240
|
|
|
/** |
1241
|
|
|
* Returns the SQL representation of Query |
1242
|
|
|
* @return string |
1243
|
|
|
*/ |
1244
|
|
|
public function __toString() |
1245
|
|
|
{ |
1246
|
|
|
return serialize($this); |
1247
|
|
|
} |
1248
|
|
|
} |
1249
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.