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