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