Query::createCommand()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidArgumentException;
13
use yii\helpers\ArrayHelper;
14
use yii\base\InvalidConfigException;
15
16
/**
17
 * Query represents a SELECT SQL statement in a way that is independent of DBMS.
18
 *
19
 * Query provides a set of methods to facilitate the specification of different clauses
20
 * in a SELECT statement. These methods can be chained together.
21
 *
22
 * By calling [[createCommand()]], we can get a [[Command]] instance which can be further
23
 * used to perform/execute the DB query against a database.
24
 *
25
 * For example,
26
 *
27
 * ```php
28
 * $query = new Query;
29
 * // compose the query
30
 * $query->select('id, name')
31
 *     ->from('user')
32
 *     ->limit(10);
33
 * // build and execute the query
34
 * $rows = $query->all();
35
 * // alternatively, you can create DB command and execute it
36
 * $command = $query->createCommand();
37
 * // $command->sql returns the actual SQL
38
 * $rows = $command->queryAll();
39
 * ```
40
 *
41
 * Query internally uses the [[QueryBuilder]] class to generate the SQL statement.
42
 *
43
 * 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).
44
 *
45
 * @property-read string[] $tablesUsedInFrom Table names indexed by aliases.
46
 *
47
 * @author Qiang Xue <[email protected]>
48
 * @author Carsten Brandt <[email protected]>
49
 * @since 2.0
50
 */
51
class Query extends Component implements QueryInterface, ExpressionInterface
52
{
53
    use QueryTrait;
54
55
    /**
56
     * @var array|null 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|null 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 = false;
71
    /**
72
     * @var array|null 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|null 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|null 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|null 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|null 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|null 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|null list of query parameter values indexed by parameter placeholders.
126
     * For example, `[':name' => 'Dan', ':age' => 31]`.
127
     */
128
    public $params = [];
129
    /**
130
     * @var int|bool|null 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|null 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|null $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 394
    public function createCommand($db = null)
153
    {
154 394
        if ($db === null) {
155 43
            $db = Yii::$app->getDb();
156
        }
157 394
        list($sql, $params) = $db->getQueryBuilder()->build($this);
158
159 394
        $command = $db->createCommand($sql, $params);
160 394
        $this->setCommandCache($command);
161
162 394
        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 898
    public function prepare($builder)
0 ignored issues
show
Unused Code introduced by
The parameter $builder is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

172
    public function prepare(/** @scrutinizer ignore-unused */ $builder)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
173
    {
174 898
        return $this;
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|null $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 12
    public function batch($batchSize = 100, $db = null)
199
    {
200 12
        return Yii::createObject([
201 12
            'class' => BatchQueryResult::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

201
            'class' => /** @scrutinizer ignore-deprecated */ BatchQueryResult::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
202 12
            'query' => $this,
203 12
            'batchSize' => $batchSize,
204 12
            'db' => $db,
205 12
            'each' => false,
206 12
        ]);
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|null $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 3
    public function each($batchSize = 100, $db = null)
227
    {
228 3
        return Yii::createObject([
229 3
            'class' => BatchQueryResult::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

229
            'class' => /** @scrutinizer ignore-deprecated */ BatchQueryResult::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
230 3
            'query' => $this,
231 3
            'batchSize' => $batchSize,
232 3
            'db' => $db,
233 3
            'each' => true,
234 3
        ]);
235
    }
236
237
    /**
238
     * Executes the query and returns all results as an array.
239
     * @param Connection|null $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 498
    public function all($db = null)
244
    {
245 498
        if ($this->emulateExecution) {
246 12
            return [];
247
        }
248
249 492
        $rows = $this->createCommand($db)->queryAll();
250
251 492
        return $this->populate($rows);
252
    }
253
254
    /**
255
     * Converts the raw query results into the format as specified by this query.
256
     * This method is internally used to convert the data fetched from database
257
     * into the format as required by this query.
258
     * @param array $rows the raw query result from database
259
     * @return array the converted query result
260
     */
261 653
    public function populate($rows)
262
    {
263 653
        if ($this->indexBy === null) {
264 644
            return $rows;
265
        }
266 27
        $result = [];
267 27
        foreach ($rows as $row) {
268 27
            $result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
269
        }
270
271 27
        return $result;
272
    }
273
274
    /**
275
     * Executes the query and returns a single row of result.
276
     * @param Connection|null $db the database connection used to generate the SQL statement.
277
     * If this parameter is not given, the `db` application component will be used.
278
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
279
     * results in nothing.
280
     */
281 501
    public function one($db = null)
282
    {
283 501
        if ($this->emulateExecution) {
284 6
            return false;
285
        }
286
287 495
        return $this->createCommand($db)->queryOne();
288
    }
289
290
    /**
291
     * Returns the query result as a scalar value.
292
     * The value returned will be the first column in the first row of the query results.
293
     * @param Connection|null $db the database connection used to generate the SQL statement.
294
     * If this parameter is not given, the `db` application component will be used.
295
     * @return string|int|null|false the value of the first column in the first row of the query result.
296
     * False is returned if the query result is empty.
297
     */
298 36
    public function scalar($db = null)
299
    {
300 36
        if ($this->emulateExecution) {
301 6
            return null;
302
        }
303
304 30
        return $this->createCommand($db)->queryScalar();
305
    }
306
307
    /**
308
     * Executes the query and returns the first column of the result.
309
     * @param Connection|null $db the database connection used to generate the SQL statement.
310
     * If this parameter is not given, the `db` application component will be used.
311
     * @return array the first column of the query result. An empty array is returned if the query results in nothing.
312
     */
313 82
    public function column($db = null)
314
    {
315 82
        if ($this->emulateExecution) {
316 6
            return [];
317
        }
318
319 76
        if ($this->indexBy === null) {
320 70
            return $this->createCommand($db)->queryColumn();
321
        }
322
323 9
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
324 9
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
325 9
                $this->select[] = key($tables) . '.' . $this->indexBy;
326
            } else {
327 3
                $this->select[] = $this->indexBy;
328
            }
329
        }
330 9
        $rows = $this->createCommand($db)->queryAll();
331 9
        $results = [];
332 9
        $column = null;
333 9
        if (is_string($this->indexBy)) {
334 9
            if (($dotPos = strpos($this->indexBy, '.')) === false) {
335 9
                $column = $this->indexBy;
336
            } else {
337 3
                $column = substr($this->indexBy, $dotPos + 1);
338
            }
339
        }
340 9
        foreach ($rows as $row) {
341 9
            $value = reset($row);
342
343 9
            if ($this->indexBy instanceof \Closure) {
344 3
                $results[call_user_func($this->indexBy, $row)] = $value;
345
            } else {
346 9
                $results[$row[$column]] = $value;
347
            }
348
        }
349
350 9
        return $results;
351
    }
352
353
    /**
354
     * Returns the number of records.
355
     * @param string $q the COUNT expression. Defaults to '*'.
356
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
357
     * @param Connection|null $db the database connection used to generate the SQL statement.
358
     * If this parameter is not given (or null), the `db` application component will be used.
359
     * @return int|string|null number of records. The result may be a string depending on the
360
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
361
     */
362 96
    public function count($q = '*', $db = null)
363
    {
364 96
        if ($this->emulateExecution) {
365 6
            return 0;
366
        }
367
368 96
        return $this->queryScalar("COUNT($q)", $db);
369
    }
370
371
    /**
372
     * Returns the sum of the specified column values.
373
     * @param string $q the column name or expression.
374
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
375
     * @param Connection|null $db the database connection used to generate the SQL statement.
376
     * If this parameter is not given, the `db` application component will be used.
377
     * @return mixed the sum of the specified column values.
378
     */
379 9
    public function sum($q, $db = null)
380
    {
381 9
        if ($this->emulateExecution) {
382 6
            return 0;
383
        }
384
385 3
        return $this->queryScalar("SUM($q)", $db);
386
    }
387
388
    /**
389
     * Returns the average of the specified column values.
390
     * @param string $q the column name or expression.
391
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
392
     * @param Connection|null $db the database connection used to generate the SQL statement.
393
     * If this parameter is not given, the `db` application component will be used.
394
     * @return mixed the average of the specified column values.
395
     */
396 9
    public function average($q, $db = null)
397
    {
398 9
        if ($this->emulateExecution) {
399 6
            return 0;
400
        }
401
402 3
        return $this->queryScalar("AVG($q)", $db);
403
    }
404
405
    /**
406
     * Returns the minimum of the specified column values.
407
     * @param string $q the column name or expression.
408
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
409
     * @param Connection|null $db the database connection used to generate the SQL statement.
410
     * If this parameter is not given, the `db` application component will be used.
411
     * @return mixed the minimum of the specified column values.
412
     */
413 9
    public function min($q, $db = null)
414
    {
415 9
        return $this->queryScalar("MIN($q)", $db);
416
    }
417
418
    /**
419
     * Returns the maximum of the specified column values.
420
     * @param string $q the column name or expression.
421
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
422
     * @param Connection|null $db the database connection used to generate the SQL statement.
423
     * If this parameter is not given, the `db` application component will be used.
424
     * @return mixed the maximum of the specified column values.
425
     */
426 9
    public function max($q, $db = null)
427
    {
428 9
        return $this->queryScalar("MAX($q)", $db);
429
    }
430
431
    /**
432
     * Returns a value indicating whether the query result contains any row of data.
433
     * @param Connection|null $db the database connection used to generate the SQL statement.
434
     * If this parameter is not given, the `db` application component will be used.
435
     * @return bool whether the query result contains any row of data.
436
     */
437 89
    public function exists($db = null)
438
    {
439 89
        if ($this->emulateExecution) {
440 6
            return false;
441
        }
442 83
        $command = $this->createCommand($db);
443 83
        $params = $command->params;
444 83
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
445 83
        $command->bindValues($params);
446 83
        return (bool) $command->queryScalar();
447
    }
448
449
    /**
450
     * Queries a scalar value by setting [[select]] first.
451
     * Restores the value of select to make this query reusable.
452
     * @param string|ExpressionInterface $selectExpression
453
     * @param Connection|null $db the database connection used to execute the query.
454
     * @return bool|string|null
455
     * @throws \Throwable if can't create command
456
     */
457 96
    protected function queryScalar($selectExpression, $db)
458
    {
459 96
        if ($this->emulateExecution) {
460 6
            return null;
461
        }
462
463
        if (
464 96
            !$this->distinct
465 96
            && empty($this->groupBy)
466 96
            && empty($this->having)
467 96
            && empty($this->union)
468
        ) {
469 95
            $select = $this->select;
470 95
            $order = $this->orderBy;
471 95
            $limit = $this->limit;
472 95
            $offset = $this->offset;
473
474 95
            $this->select = [$selectExpression];
475 95
            $this->orderBy = null;
476 95
            $this->limit = null;
477 95
            $this->offset = null;
478
479 95
            $e = null;
480
            try {
481 95
                $command = $this->createCommand($db);
482
            } catch (\Exception $e) {
483
                // throw it later (for PHP < 7.0)
484
            } catch (\Throwable $e) {
485
                // throw it later
486
            }
487
488 95
            $this->select = $select;
489 95
            $this->orderBy = $order;
490 95
            $this->limit = $limit;
491 95
            $this->offset = $offset;
492
493 95
            if ($e !== null) {
494
                throw $e;
495
            }
496
497 95
            return $command->queryScalar();
498
        }
499
500 7
        $command = (new self())
501 7
            ->select([$selectExpression])
502 7
            ->from(['c' => $this])
503 7
            ->createCommand($db);
504 7
        $this->setCommandCache($command);
505
506 7
        return $command->queryScalar();
507
    }
508
509
    /**
510
     * Returns table names used in [[from]] indexed by aliases.
511
     * Both aliases and names are enclosed into {{ and }}.
512
     * @return string[] table names indexed by aliases
513
     * @throws \yii\base\InvalidConfigException
514
     * @since 2.0.12
515
     */
516 120
    public function getTablesUsedInFrom()
517
    {
518 120
        if (empty($this->from)) {
519
            return [];
520
        }
521
522 120
        if (is_array($this->from)) {
0 ignored issues
show
introduced by
The condition is_array($this->from) is always true.
Loading history...
523 84
            $tableNames = $this->from;
524 36
        } elseif (is_string($this->from)) {
525 24
            $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
526 12
        } elseif ($this->from instanceof Expression) {
527 6
            $tableNames = [$this->from];
528
        } else {
529 6
            throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
530
        }
531
532 114
        return $this->cleanUpTableNames($tableNames);
533
    }
534
535
    /**
536
     * Clean up table names and aliases
537
     * Both aliases and names are enclosed into {{ and }}.
538
     * @param array $tableNames non-empty array
539
     * @return string[] table names indexed by aliases
540
     * @since 2.0.14
541
     */
542 287
    protected function cleanUpTableNames($tableNames)
543
    {
544 287
        $cleanedUpTableNames = [];
545 287
        foreach ($tableNames as $alias => $tableName) {
546 287
            if (is_string($tableName) && !is_string($alias)) {
547 227
                $pattern = <<<PATTERN
548
~
549
^
550
\s*
551
(
552
(?:['"`\[]|{{)
553
.*?
554
(?:['"`\]]|}})
555
|
556
\(.*?\)
557
|
558
.*?
559
)
560
(?:
561
(?:
562
    \s+
563
    (?:as)?
564
    \s*
565
)
566
(
567
   (?:['"`\[]|{{)
568
    .*?
569
    (?:['"`\]]|}})
570
    |
571
    .*?
572
)
573
)?
574
\s*
575
$
576
~iux
577 227
PATTERN;
578 227
                if (preg_match($pattern, $tableName, $matches)) {
579 227
                    if (isset($matches[2])) {
580 18
                        list(, $tableName, $alias) = $matches;
581
                    } else {
582 221
                        $tableName = $alias = $matches[1];
583
                    }
584
                }
585
            }
586
587
588 287
            if ($tableName instanceof Expression) {
589 12
                if (!is_string($alias)) {
590 6
                    throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
591
                }
592 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
593 275
            } elseif ($tableName instanceof self) {
594 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
595
            } else {
596 269
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
597
            }
598
        }
599
600 281
        return $cleanedUpTableNames;
601
    }
602
603
    /**
604
     * Ensures name is wrapped with {{ and }}
605
     * @param string $name
606
     * @return string
607
     */
608 281
    private function ensureNameQuoted($name)
609
    {
610 281
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
611 281
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
612 269
            return '{{' . $name . '}}';
613
        }
614
615 30
        return $name;
616
    }
617
618
    /**
619
     * Sets the SELECT part of the query.
620
     * @param string|array|ExpressionInterface $columns the columns to be selected.
621
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
622
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
623
     * The method will automatically quote the column names unless a column contains some parenthesis
624
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
625
     * an [[ExpressionInterface]] object.
626
     *
627
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
628
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
629
     *
630
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
631
     * does not need alias, do not use a string key).
632
     *
633
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
634
     * as a `Query` instance representing the sub-query.
635
     *
636
     * @param string|null $option additional option that should be appended to the 'SELECT' keyword. For example,
637
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
638
     * @return $this the query object itself
639
     */
640 433
    public function select($columns, $option = null)
641
    {
642 433
        $this->select = $this->normalizeSelect($columns);
643 433
        $this->selectOption = $option;
644 433
        return $this;
645
    }
646
647
    /**
648
     * Add more columns to the SELECT part of the query.
649
     *
650
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
651
     * if you want to select all remaining columns too:
652
     *
653
     * ```php
654
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
655
     * ```
656
     *
657
     * @param string|array|ExpressionInterface $columns the columns to add to the select. See [[select()]] for more
658
     * details about the format of this parameter.
659
     * @return $this the query object itself
660
     * @see select()
661
     */
662 9
    public function addSelect($columns)
663
    {
664 9
        if ($this->select === null) {
665 3
            return $this->select($columns);
666
        }
667 9
        if (!is_array($this->select)) {
0 ignored issues
show
introduced by
The condition is_array($this->select) is always true.
Loading history...
668
            $this->select = $this->normalizeSelect($this->select);
669
        }
670 9
        $this->select = array_merge($this->select, $this->normalizeSelect($columns));
671
672 9
        return $this;
673
    }
674
675
    /**
676
     * Normalizes the SELECT columns passed to [[select()]] or [[addSelect()]].
677
     *
678
     * @param string|array|ExpressionInterface $columns
679
     * @return array
680
     * @since 2.0.21
681
     */
682 433
    protected function normalizeSelect($columns)
683
    {
684 433
        if ($columns instanceof ExpressionInterface) {
685 3
            $columns = [$columns];
686 433
        } elseif (!is_array($columns)) {
687 121
            $columns = preg_split('/\s*,\s*/', trim((string)$columns), -1, PREG_SPLIT_NO_EMPTY);
688
        }
689 433
        $select = [];
690 433
        foreach ($columns as $columnAlias => $columnDefinition) {
691 430
            if (is_string($columnAlias)) {
692
                // Already in the normalized format, good for them
693 56
                $select[$columnAlias] = $columnDefinition;
694 56
                continue;
695
            }
696 425
            if (is_string($columnDefinition)) {
697
                if (
698 422
                    preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $columnDefinition, $matches) &&
699 422
                    !preg_match('/^\d+$/', $matches[2]) &&
700 422
                    strpos($matches[2], '.') === false
701
                ) {
702
                    // Using "columnName as alias" or "columnName alias" syntax
703 21
                    $select[$matches[2]] = $matches[1];
704 21
                    continue;
705
                }
706 416
                if (strpos($columnDefinition, '(') === false) {
707
                    // Normal column name, just alias it to itself to ensure it's not selected twice
708 406
                    $select[$columnDefinition] = $columnDefinition;
709 406
                    continue;
710
                }
711
            }
712
            // Either a string calling a function, DB expression, or sub-query
713 36
            $select[] = $columnDefinition;
714
        }
715 433
        return $select;
716
    }
717
718
    /**
719
     * Returns unique column names excluding duplicates.
720
     * Columns to be removed:
721
     * - if column definition already present in SELECT part with same alias
722
     * - if column definition without alias already present in SELECT part without alias too
723
     * @param array $columns the columns to be merged to the select.
724
     * @since 2.0.14
725
     * @deprecated in 2.0.21
726
     */
727
    protected function getUniqueColumns($columns)
728
    {
729
        $unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
0 ignored issues
show
Deprecated Code introduced by
The function yii\db\Query::getUnaliasedColumnsFromSelect() has been deprecated: in 2.0.21 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

729
        $unaliasedColumns = /** @scrutinizer ignore-deprecated */ $this->getUnaliasedColumnsFromSelect();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
730
731
        $result = [];
732
        foreach ($columns as $columnAlias => $columnDefinition) {
733
            if (!$columnDefinition instanceof Query) {
734
                if (is_string($columnAlias)) {
735
                    $existsInSelect = isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition;
736
                    if ($existsInSelect) {
737
                        continue;
738
                    }
739
                } elseif (is_int($columnAlias)) {
740
                    $existsInSelect = in_array($columnDefinition, $unaliasedColumns, true);
741
                    $existsInResultSet = in_array($columnDefinition, $result, true);
742
                    if ($existsInSelect || $existsInResultSet) {
743
                        continue;
744
                    }
745
                }
746
            }
747
748
            $result[$columnAlias] = $columnDefinition;
749
        }
750
        return $result;
751
    }
752
753
    /**
754
     * @return array List of columns without aliases from SELECT statement.
755
     * @since 2.0.14
756
     * @deprecated in 2.0.21
757
     */
758
    protected function getUnaliasedColumnsFromSelect()
759
    {
760
        $result = [];
761
        if (is_array($this->select)) {
762
            foreach ($this->select as $name => $value) {
763
                if (is_int($name)) {
764
                    $result[] = $value;
765
                }
766
            }
767
        }
768
        return array_unique($result);
769
    }
770
771
    /**
772
     * Sets the value indicating whether to SELECT DISTINCT or not.
773
     * @param bool $value whether to SELECT DISTINCT or not.
774
     * @return $this the query object itself
775
     */
776 9
    public function distinct($value = true)
777
    {
778 9
        $this->distinct = $value;
779 9
        return $this;
780
    }
781
782
    /**
783
     * Sets the FROM part of the query.
784
     * @param string|array|ExpressionInterface $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
785
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
786
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
787
     * The method will automatically quote the table names unless it contains some parenthesis
788
     * (which means the table is given as a sub-query or DB expression).
789
     *
790
     * When the tables are specified as an array, you may also use the array keys as the table aliases
791
     * (if a table does not need alias, do not use a string key).
792
     *
793
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
794
     * as the alias for the sub-query.
795
     *
796
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[ExpressionInterface]].
797
     *
798
     * Here are some examples:
799
     *
800
     * ```php
801
     * // SELECT * FROM  `user` `u`, `profile`;
802
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
803
     *
804
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
805
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
806
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
807
     *
808
     * // subquery can also be a string with plain SQL wrapped in parenthesis
809
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
810
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
811
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
812
     * ```
813
     *
814
     * @return $this the query object itself
815
     */
816 491
    public function from($tables)
817
    {
818 491
        if ($tables instanceof ExpressionInterface) {
819 6
            $tables = [$tables];
820
        }
821 491
        if (is_string($tables)) {
822 435
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
823
        }
824 491
        $this->from = $tables;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tables can also be of type string. However, the property $from is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
825 491
        return $this;
826
    }
827
828
    /**
829
     * Sets the WHERE part of the query.
830
     *
831
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
832
     * specifying the values to be bound to the query.
833
     *
834
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
835
     *
836
     * {@inheritdoc}
837
     *
838
     * @param string|array|ExpressionInterface $condition the conditions that should be put in the WHERE part.
839
     * @param array $params the parameters (name => value) to be bound to the query.
840
     * @return $this the query object itself
841
     * @see andWhere()
842
     * @see orWhere()
843
     * @see QueryInterface::where()
844
     */
845 882
    public function where($condition, $params = [])
846
    {
847 882
        $this->where = $condition;
848 882
        $this->addParams($params);
849 882
        return $this;
850
    }
851
852
    /**
853
     * Adds an additional WHERE condition to the existing one.
854
     * The new condition and the existing one will be joined using the `AND` operator.
855
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
856
     * on how to specify this parameter.
857
     * @param array $params the parameters (name => value) to be bound to the query.
858
     * @return $this the query object itself
859
     * @see where()
860
     * @see orWhere()
861
     */
862 459
    public function andWhere($condition, $params = [])
863
    {
864 459
        if ($this->where === null) {
865 396
            $this->where = $condition;
866 135
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
867 43
            $this->where[] = $condition;
868
        } else {
869 135
            $this->where = ['and', $this->where, $condition];
870
        }
871 459
        $this->addParams($params);
872 459
        return $this;
873
    }
874
875
    /**
876
     * Adds an additional WHERE condition to the existing one.
877
     * The new condition and the existing one will be joined using the `OR` operator.
878
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
879
     * on how to specify this parameter.
880
     * @param array $params the parameters (name => value) to be bound to the query.
881
     * @return $this the query object itself
882
     * @see where()
883
     * @see andWhere()
884
     */
885 8
    public function orWhere($condition, $params = [])
886
    {
887 8
        if ($this->where === null) {
888
            $this->where = $condition;
889
        } else {
890 8
            $this->where = ['or', $this->where, $condition];
891
        }
892 8
        $this->addParams($params);
893 8
        return $this;
894
    }
895
896
    /**
897
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
898
     *
899
     * It adds an additional WHERE condition for the given field and determines the comparison operator
900
     * based on the first few characters of the given value.
901
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
902
     * The new condition and the existing one will be joined using the `AND` operator.
903
     *
904
     * The comparison operator is intelligently determined based on the first few characters in the given value.
905
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
906
     *
907
     * - `<`: the column must be less than the given value.
908
     * - `>`: the column must be greater than the given value.
909
     * - `<=`: the column must be less than or equal to the given value.
910
     * - `>=`: the column must be greater than or equal to the given value.
911
     * - `<>`: the column must not be the same as the given value.
912
     * - `=`: the column must be equal to the given value.
913
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
914
     *
915
     * @param string $name the column name.
916
     * @param string $value the column value optionally prepended with the comparison operator.
917
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
918
     * Defaults to `=`, performing an exact match.
919
     * @return $this The query object itself
920
     * @since 2.0.8
921
     */
922 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
923
    {
924 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', (string)$value, $matches)) {
925 3
            $operator = $matches[1];
926 3
            $value = substr($value, strlen($operator));
927
        } else {
928 3
            $operator = $defaultOperator;
929
        }
930
931 3
        return $this->andFilterWhere([$operator, $name, $value]);
932
    }
933
934
    /**
935
     * Appends a JOIN part to the query.
936
     * The first parameter specifies what type of join it is.
937
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
938
     * @param string|array $table the table or sub-query to be joined.
939
     *
940
     * Use a string to represent the name of the table to be joined.
941
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
942
     * The method will automatically quote the table name unless it contains some parenthesis
943
     * (which means the table is given as a sub-query or DB expression).
944
     *
945
     * You may also specify the table as an array with one element, using the array key as the table alias
946
     * (e.g. ['u' => 'user']).
947
     *
948
     * To join a sub-query, use an array with one element, with the value set to a [[Query]] object
949
     * representing the sub-query, and the corresponding key representing the alias.
950
     *
951
     * @param string|array $on the join condition that should appear in the ON part.
952
     * Please refer to [[where()]] on how to specify this parameter.
953
     *
954
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
955
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
956
     * match the `post.author_id` column value against the string `'user.id'`.
957
     * It is recommended to use the string syntax here which is more suited for a join:
958
     *
959
     * ```php
960
     * 'post.author_id = user.id'
961
     * ```
962
     *
963
     * @param array $params the parameters (name => value) to be bound to the query.
964
     * @return $this the query object itself
965
     */
966 90
    public function join($type, $table, $on = '', $params = [])
967
    {
968 90
        $this->join[] = [$type, $table, $on];
969 90
        return $this->addParams($params);
970
    }
971
972
    /**
973
     * Appends an INNER JOIN part to the query.
974
     * @param string|array $table the table or sub-query to be joined.
975
     *
976
     * Use a string to represent the name of the table to be joined.
977
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
978
     * The method will automatically quote the table name unless it contains some parenthesis
979
     * (which means the table is given as a sub-query or DB expression).
980
     *
981
     * You may also specify the table as an array with one element, using the array key as the table alias
982
     * (e.g. ['u' => 'user']).
983
     *
984
     * To join a sub-query, use an array with one element, with the value set to a [[Query]] object
985
     * representing the sub-query, and the corresponding key representing the alias.
986
     *
987
     * @param string|array $on the join condition that should appear in the ON part.
988
     * Please refer to [[join()]] on how to specify this parameter.
989
     * @param array $params the parameters (name => value) to be bound to the query.
990
     * @return $this the query object itself
991
     */
992 6
    public function innerJoin($table, $on = '', $params = [])
993
    {
994 6
        $this->join[] = ['INNER JOIN', $table, $on];
995 6
        return $this->addParams($params);
996
    }
997
998
    /**
999
     * Appends a LEFT OUTER JOIN part to the query.
1000
     * @param string|array $table the table or sub-query to be joined.
1001
     *
1002
     * Use a string to represent the name of the table to be joined.
1003
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
1004
     * The method will automatically quote the table name unless it contains some parenthesis
1005
     * (which means the table is given as a sub-query or DB expression).
1006
     *
1007
     * You may also specify the table as an array with one element, using the array key as the table alias
1008
     * (e.g. ['u' => 'user']).
1009
     *
1010
     * To join a sub-query, use an array with one element, with the value set to a [[Query]] object
1011
     * representing the sub-query, and the corresponding key representing the alias.
1012
     *
1013
     * @param string|array $on the join condition that should appear in the ON part.
1014
     * Please refer to [[join()]] on how to specify this parameter.
1015
     * @param array $params the parameters (name => value) to be bound to the query
1016
     * @return $this the query object itself
1017
     */
1018 3
    public function leftJoin($table, $on = '', $params = [])
1019
    {
1020 3
        $this->join[] = ['LEFT JOIN', $table, $on];
1021 3
        return $this->addParams($params);
1022
    }
1023
1024
    /**
1025
     * Appends a RIGHT OUTER JOIN part to the query.
1026
     * @param string|array $table the table or sub-query to be joined.
1027
     *
1028
     * Use a string to represent the name of the table to be joined.
1029
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
1030
     * The method will automatically quote the table name unless it contains some parenthesis
1031
     * (which means the table is given as a sub-query or DB expression).
1032
     *
1033
     * You may also specify the table as an array with one element, using the array key as the table alias
1034
     * (e.g. ['u' => 'user']).
1035
     *
1036
     * To join a sub-query, use an array with one element, with the value set to a [[Query]] object
1037
     * representing the sub-query, and the corresponding key representing the alias.
1038
     *
1039
     * @param string|array $on the join condition that should appear in the ON part.
1040
     * Please refer to [[join()]] on how to specify this parameter.
1041
     * @param array $params the parameters (name => value) to be bound to the query
1042
     * @return $this the query object itself
1043
     */
1044
    public function rightJoin($table, $on = '', $params = [])
1045
    {
1046
        $this->join[] = ['RIGHT JOIN', $table, $on];
1047
        return $this->addParams($params);
1048
    }
1049
1050
    /**
1051
     * Sets the GROUP BY part of the query.
1052
     * @param string|array|ExpressionInterface|null $columns the columns to be grouped by.
1053
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
1054
     * The method will automatically quote the column names unless a column contains some parenthesis
1055
     * (which means the column contains a DB expression).
1056
     *
1057
     * Note that if your group-by is an expression containing commas, you should always use an array
1058
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
1059
     * the group-by columns.
1060
     *
1061
     * Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1062
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1063
     * @return $this the query object itself
1064
     * @see addGroupBy()
1065
     */
1066 30
    public function groupBy($columns)
1067
    {
1068 30
        if ($columns instanceof ExpressionInterface) {
1069 3
            $columns = [$columns];
1070 30
        } elseif (!is_array($columns) && !is_null($columns)) {
1071 30
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1072
        }
1073 30
        $this->groupBy = $columns;
1074 30
        return $this;
1075
    }
1076
1077
    /**
1078
     * Adds additional group-by columns to the existing ones.
1079
     * @param string|array|ExpressionInterface $columns additional columns to be grouped by.
1080
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
1081
     * The method will automatically quote the column names unless a column contains some parenthesis
1082
     * (which means the column contains a DB expression).
1083
     *
1084
     * Note that if your group-by is an expression containing commas, you should always use an array
1085
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
1086
     * the group-by columns.
1087
     *
1088
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1089
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1090
     * @return $this the query object itself
1091
     * @see groupBy()
1092
     */
1093 3
    public function addGroupBy($columns)
1094
    {
1095 3
        if ($columns instanceof ExpressionInterface) {
1096
            $columns = [$columns];
1097 3
        } elseif (!is_array($columns)) {
1098 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1099
        }
1100 3
        if ($this->groupBy === null) {
1101
            $this->groupBy = $columns;
1102
        } else {
1103 3
            $this->groupBy = array_merge($this->groupBy, $columns);
1104
        }
1105
1106 3
        return $this;
1107
    }
1108
1109
    /**
1110
     * Sets the HAVING part of the query.
1111
     * @param string|array|ExpressionInterface $condition the conditions to be put after HAVING.
1112
     * Please refer to [[where()]] on how to specify this parameter.
1113
     * @param array $params the parameters (name => value) to be bound to the query.
1114
     * @return $this the query object itself
1115
     * @see andHaving()
1116
     * @see orHaving()
1117
     */
1118 13
    public function having($condition, $params = [])
1119
    {
1120 13
        $this->having = $condition;
1121 13
        $this->addParams($params);
1122 13
        return $this;
1123
    }
1124
1125
    /**
1126
     * Adds an additional HAVING condition to the existing one.
1127
     * The new condition and the existing one will be joined using the `AND` operator.
1128
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1129
     * on how to specify this parameter.
1130
     * @param array $params the parameters (name => value) to be bound to the query.
1131
     * @return $this the query object itself
1132
     * @see having()
1133
     * @see orHaving()
1134
     */
1135 3
    public function andHaving($condition, $params = [])
1136
    {
1137 3
        if ($this->having === null) {
1138
            $this->having = $condition;
1139
        } else {
1140 3
            $this->having = ['and', $this->having, $condition];
1141
        }
1142 3
        $this->addParams($params);
1143 3
        return $this;
1144
    }
1145
1146
    /**
1147
     * Adds an additional HAVING condition to the existing one.
1148
     * The new condition and the existing one will be joined using the `OR` operator.
1149
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1150
     * on how to specify this parameter.
1151
     * @param array $params the parameters (name => value) to be bound to the query.
1152
     * @return $this the query object itself
1153
     * @see having()
1154
     * @see andHaving()
1155
     */
1156 3
    public function orHaving($condition, $params = [])
1157
    {
1158 3
        if ($this->having === null) {
1159
            $this->having = $condition;
1160
        } else {
1161 3
            $this->having = ['or', $this->having, $condition];
1162
        }
1163 3
        $this->addParams($params);
1164 3
        return $this;
1165
    }
1166
1167
    /**
1168
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1169
     *
1170
     * This method is similar to [[having()]]. The main difference is that this method will
1171
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1172
     * for building query conditions based on filter values entered by users.
1173
     *
1174
     * The following code shows the difference between this method and [[having()]]:
1175
     *
1176
     * ```php
1177
     * // HAVING `age`=:age
1178
     * $query->filterHaving(['name' => null, 'age' => 20]);
1179
     * // HAVING `age`=:age
1180
     * $query->having(['age' => 20]);
1181
     * // HAVING `name` IS NULL AND `age`=:age
1182
     * $query->having(['name' => null, 'age' => 20]);
1183
     * ```
1184
     *
1185
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1186
     *
1187
     * @param array $condition the conditions that should be put in the HAVING part.
1188
     * See [[having()]] on how to specify this parameter.
1189
     * @return $this the query object itself
1190
     * @see having()
1191
     * @see andFilterHaving()
1192
     * @see orFilterHaving()
1193
     * @since 2.0.11
1194
     */
1195 6
    public function filterHaving(array $condition)
1196
    {
1197 6
        $condition = $this->filterCondition($condition);
1198 6
        if ($condition !== []) {
1199 6
            $this->having($condition);
1200
        }
1201
1202 6
        return $this;
1203
    }
1204
1205
    /**
1206
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1207
     * The new condition and the existing one will be joined using the `AND` operator.
1208
     *
1209
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1210
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1211
     * for building query conditions based on filter values entered by users.
1212
     *
1213
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1214
     * on how to specify this parameter.
1215
     * @return $this the query object itself
1216
     * @see filterHaving()
1217
     * @see orFilterHaving()
1218
     * @since 2.0.11
1219
     */
1220 6
    public function andFilterHaving(array $condition)
1221
    {
1222 6
        $condition = $this->filterCondition($condition);
1223 6
        if ($condition !== []) {
1224
            $this->andHaving($condition);
1225
        }
1226
1227 6
        return $this;
1228
    }
1229
1230
    /**
1231
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1232
     * The new condition and the existing one will be joined using the `OR` operator.
1233
     *
1234
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1235
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1236
     * for building query conditions based on filter values entered by users.
1237
     *
1238
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1239
     * on how to specify this parameter.
1240
     * @return $this the query object itself
1241
     * @see filterHaving()
1242
     * @see andFilterHaving()
1243
     * @since 2.0.11
1244
     */
1245 6
    public function orFilterHaving(array $condition)
1246
    {
1247 6
        $condition = $this->filterCondition($condition);
1248 6
        if ($condition !== []) {
1249
            $this->orHaving($condition);
1250
        }
1251
1252 6
        return $this;
1253
    }
1254
1255
    /**
1256
     * Appends a SQL statement using UNION operator.
1257
     * @param string|Query $sql the SQL statement to be appended using UNION
1258
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1259
     * @return $this the query object itself
1260
     */
1261 16
    public function union($sql, $all = false)
1262
    {
1263 16
        $this->union[] = ['query' => $sql, 'all' => $all];
1264 16
        return $this;
1265
    }
1266
1267
    /**
1268
     * Prepends a SQL statement using WITH syntax.
1269
     * @param string|Query $query the SQL statement to be prepended using WITH
1270
     * @param string $alias query alias in WITH construction
1271
     * @param bool $recursive TRUE if using WITH RECURSIVE and FALSE if using WITH
1272
     * @return $this the query object itself
1273
     * @since 2.0.35
1274
     */
1275 9
    public function withQuery($query, $alias, $recursive = false)
1276
    {
1277 9
        $this->withQueries[] = ['query' => $query, 'alias' => $alias, 'recursive' => $recursive];
1278 9
        return $this;
1279
    }
1280
1281
    /**
1282
     * Sets the parameters to be bound to the query.
1283
     * @param array $params list of query parameter values indexed by parameter placeholders.
1284
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1285
     * @return $this the query object itself
1286
     * @see addParams()
1287
     */
1288 6
    public function params($params)
1289
    {
1290 6
        $this->params = $params;
1291 6
        return $this;
1292
    }
1293
1294
    /**
1295
     * Adds additional parameters to be bound to the query.
1296
     * @param array $params list of query parameter values indexed by parameter placeholders.
1297
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1298
     * @return $this the query object itself
1299
     * @see params()
1300
     */
1301 1230
    public function addParams($params)
1302
    {
1303 1230
        if (!empty($params)) {
1304 90
            if (empty($this->params)) {
1305 90
                $this->params = $params;
1306
            } else {
1307 6
                foreach ($params as $name => $value) {
1308 6
                    if (is_int($name)) {
1309
                        $this->params[] = $value;
1310
                    } else {
1311 6
                        $this->params[$name] = $value;
1312
                    }
1313
                }
1314
            }
1315
        }
1316
1317 1230
        return $this;
1318
    }
1319
1320
    /**
1321
     * Enables query cache for this Query.
1322
     * @param int|true $duration the number of seconds that query results can remain valid in cache.
1323
     * Use 0 to indicate that the cached data will never expire.
1324
     * Use a negative number to indicate that query cache should not be used.
1325
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
1326
     * Defaults to `true`.
1327
     * @param \yii\caching\Dependency|null $dependency the cache dependency associated with the cached result.
1328
     * @return $this the Query object itself
1329
     * @since 2.0.14
1330
     */
1331 3
    public function cache($duration = true, $dependency = null)
1332
    {
1333 3
        $this->queryCacheDuration = $duration;
1334 3
        $this->queryCacheDependency = $dependency;
1335 3
        return $this;
1336
    }
1337
1338
    /**
1339
     * Disables query cache for this Query.
1340
     * @return $this the Query object itself
1341
     * @since 2.0.14
1342
     */
1343 32
    public function noCache()
1344
    {
1345 32
        $this->queryCacheDuration = -1;
1346 32
        return $this;
1347
    }
1348
1349
    /**
1350
     * Sets $command cache, if this query has enabled caching.
1351
     *
1352
     * @param Command $command
1353
     * @return Command
1354
     * @since 2.0.14
1355
     */
1356 876
    protected function setCommandCache($command)
1357
    {
1358 876
        if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
1359 32
            $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
1360 32
            $command->cache($duration, $this->queryCacheDependency);
0 ignored issues
show
Bug introduced by
It seems like $duration can also be of type false; however, parameter $duration of yii\db\Command::cache() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1360
            $command->cache(/** @scrutinizer ignore-type */ $duration, $this->queryCacheDependency);
Loading history...
1361
        }
1362
1363 876
        return $command;
1364
    }
1365
1366
    /**
1367
     * Creates a new Query object and copies its property values from an existing one.
1368
     * The properties being copies are the ones to be used by query builders.
1369
     * @param Query $from the source query object
1370
     * @return Query the new Query object
1371
     */
1372 520
    public static function create($from)
1373
    {
1374 520
        return new self([
1375 520
            'where' => $from->where,
1376 520
            'limit' => $from->limit,
1377 520
            'offset' => $from->offset,
1378 520
            'orderBy' => $from->orderBy,
1379 520
            'indexBy' => $from->indexBy,
1380 520
            'select' => $from->select,
1381 520
            'selectOption' => $from->selectOption,
1382 520
            'distinct' => $from->distinct,
1383 520
            'from' => $from->from,
1384 520
            'groupBy' => $from->groupBy,
1385 520
            'join' => $from->join,
1386 520
            'having' => $from->having,
1387 520
            'union' => $from->union,
1388 520
            'params' => $from->params,
1389 520
            'withQueries' => $from->withQueries,
1390 520
        ]);
1391
    }
1392
1393
    /**
1394
     * Returns the SQL representation of Query
1395
     * @return string
1396
     */
1397
    public function __toString()
1398
    {
1399
        return serialize($this);
1400
    }
1401
}
1402