Completed
Push — master ( 807945...ef8f61 )
by Carsten
11:15
created

Query::addParams()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.0342

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
ccs 8
cts 9
cp 0.8889
cc 5
eloc 11
nc 3
nop 1
crap 5.0342
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\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 string[] $tablesUsedInFrom Table names indexed by aliases. This property is read-only.
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 the columns being selected. For example, `['id', 'name']`.
57
     * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
58
     * @see select()
59
     */
60
    public $select;
61
    /**
62
     * @var string additional option that should be appended to the 'SELECT' keyword. For example,
63
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
64
     */
65
    public $selectOption;
66
    /**
67
     * @var bool whether to select distinct rows of data only. If this is set true,
68
     * the SELECT clause would be changed to SELECT DISTINCT.
69
     */
70
    public $distinct;
71
    /**
72
     * @var array the table(s) to be selected from. For example, `['user', 'post']`.
73
     * This is used to construct the FROM clause in a SQL statement.
74
     * @see from()
75
     */
76
    public $from;
77
    /**
78
     * @var array how to group the query results. For example, `['company', 'department']`.
79
     * This is used to construct the GROUP BY clause in a SQL statement.
80
     */
81
    public $groupBy;
82
    /**
83
     * @var array how to join with other tables. Each array element represents the specification
84
     * of one join which has the following structure:
85
     *
86
     * ```php
87
     * [$joinType, $tableName, $joinCondition]
88
     * ```
89
     *
90
     * For example,
91
     *
92
     * ```php
93
     * [
94
     *     ['INNER JOIN', 'user', 'user.id = author_id'],
95
     *     ['LEFT JOIN', 'team', 'team.id = team_id'],
96
     * ]
97
     * ```
98
     */
99
    public $join;
100
    /**
101
     * @var string|array|ExpressionInterface the condition to be applied in the GROUP BY clause.
102
     * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
103
     */
104
    public $having;
105
    /**
106
     * @var array this is used to construct the UNION clause(s) in a SQL statement.
107
     * Each array element is an array of the following structure:
108
     *
109
     * - `query`: either a string or a [[Query]] object representing a query
110
     * - `all`: boolean, whether it should be `UNION ALL` or `UNION`
111
     */
112
    public $union;
113
    /**
114
     * @var array list of query parameter values indexed by parameter placeholders.
115
     * For example, `[':name' => 'Dan', ':age' => 31]`.
116
     */
117
    public $params = [];
118
    /**
119
     * @var int|true the default number of seconds that query results can remain valid in cache.
120
     * Use 0 to indicate that the cached data will never expire.
121
     * Use a negative number to indicate that query cache should not be used.
122
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
123
     * @see cache()
124
     */
125
    public $queryCacheDuration;
126
    /**
127
     * @var \yii\caching\Dependency the dependency to be associated with the cached query result for this query
128
     * @see cache()
129
     */
130
    public $queryCacheDependency;
131
132
    /**
133
     * Creates a DB command that can be used to execute this query.
134
     * @param Connection $db the database connection used to generate the SQL statement.
135
     * If this parameter is not given, the `db` application component will be used.
136
     * @return Command the created DB command instance.
137
     */
138 363
    public function createCommand($db = null)
139
    {
140 363
        if ($db === null) {
141 34
            $db = Yii::$app->getDb();
142
        }
143 363
        list($sql, $params) = $db->getQueryBuilder()->build($this);
144
145 363
        $command = $db->createCommand($sql, $params);
146 363
        $this->setCommandCache($command);
147
148 363
        return $command;
149
    }
150
151
    /**
152
     * Prepares for building SQL.
153
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
154
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
155
     * @param QueryBuilder $builder
156
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
157
     */
158 772
    public function prepare($builder)
0 ignored issues
show
Unused Code introduced by
The parameter $builder is not used and could be removed.

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

Loading history...
159
    {
160 772
        return $this;
161
    }
162
163
    /**
164
     * Starts a batch query.
165
     *
166
     * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
167
     * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
168
     * and can be traversed to retrieve the data in batches.
169
     *
170
     * For example,
171
     *
172
     * ```php
173
     * $query = (new Query)->from('user');
174
     * foreach ($query->batch() as $rows) {
175
     *     // $rows is an array of 100 or fewer rows from user table
176
     * }
177
     * ```
178
     *
179
     * @param int $batchSize the number of records to be fetched in each batch.
180
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
181
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
182
     * and can be traversed to retrieve the data in batches.
183
     */
184 6
    public function batch($batchSize = 100, $db = null)
185
    {
186 6
        return Yii::createObject([
187 6
            'class' => BatchQueryResult::className(),
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: 2.0.14 Use `::class`.

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

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

Loading history...
188 6
            'query' => $this,
189 6
            'batchSize' => $batchSize,
190 6
            'db' => $db,
191
            'each' => false,
192
        ]);
193
    }
194
195
    /**
196
     * Starts a batch query and retrieves data row by row.
197
     *
198
     * This method is similar to [[batch()]] except that in each iteration of the result,
199
     * only one row of data is returned. For example,
200
     *
201
     * ```php
202
     * $query = (new Query)->from('user');
203
     * foreach ($query->each() as $row) {
204
     * }
205
     * ```
206
     *
207
     * @param int $batchSize the number of records to be fetched in each batch.
208
     * @param Connection $db the database connection. If not set, the "db" application component will be used.
209
     * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
210
     * and can be traversed to retrieve the data in batches.
211
     */
212 3
    public function each($batchSize = 100, $db = null)
213
    {
214 3
        return Yii::createObject([
215 3
            'class' => BatchQueryResult::className(),
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: 2.0.14 Use `::class`.

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

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

Loading history...
216 3
            'query' => $this,
217 3
            'batchSize' => $batchSize,
218 3
            'db' => $db,
219
            'each' => true,
220
        ]);
221
    }
222
223
    /**
224
     * Executes the query and returns all results as an array.
225
     * @param Connection $db the database connection used to generate the SQL statement.
226
     * If this parameter is not given, the `db` application component will be used.
227
     * @return array the query results. If the query results in nothing, an empty array will be returned.
228
     */
229 424
    public function all($db = null)
230
    {
231 424
        if ($this->emulateExecution) {
232 9
            return [];
233
        }
234 418
        $rows = $this->createCommand($db)->queryAll();
235 418
        return $this->populate($rows);
236
    }
237
238
    /**
239
     * Converts the raw query results into the format as specified by this query.
240
     * This method is internally used to convert the data fetched from database
241
     * into the format as required by this query.
242
     * @param array $rows the raw query result from database
243
     * @return array the converted query result
244
     */
245 548
    public function populate($rows)
246
    {
247 548
        if ($this->indexBy === null) {
248 542
            return $rows;
249
        }
250 21
        $result = [];
251 21
        foreach ($rows as $row) {
252 21
            $result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
0 ignored issues
show
Documentation introduced by
$this->indexBy is of type callable, but the function expects a string|object<Closure>|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
253
        }
254
255 21
        return $result;
256
    }
257
258
    /**
259
     * Executes the query and returns a single row of result.
260
     * @param Connection $db the database connection used to generate the SQL statement.
261
     * If this parameter is not given, the `db` application component will be used.
262
     * @return array|bool the first row (in terms of an array) of the query result. False is returned if the query
263
     * results in nothing.
264
     */
265 451
    public function one($db = null)
266
    {
267 451
        if ($this->emulateExecution) {
268 6
            return false;
269
        }
270
271 445
        return $this->createCommand($db)->queryOne();
272
    }
273
274
    /**
275
     * Returns the query result as a scalar value.
276
     * The value returned will be the first column in the first row of the query results.
277
     * @param Connection $db the database connection used to generate the SQL statement.
278
     * If this parameter is not given, the `db` application component will be used.
279
     * @return string|null|false the value of the first column in the first row of the query result.
280
     * False is returned if the query result is empty.
281
     */
282 30
    public function scalar($db = null)
283
    {
284 30
        if ($this->emulateExecution) {
285 6
            return null;
286
        }
287
288 24
        return $this->createCommand($db)->queryScalar();
289
    }
290
291
    /**
292
     * Executes the query and returns the first column of the result.
293
     * @param Connection $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 array the first column of the query result. An empty array is returned if the query results in nothing.
296
     */
297 73
    public function column($db = null)
298
    {
299 73
        if ($this->emulateExecution) {
300 6
            return [];
301
        }
302
303 67
        if ($this->indexBy === null) {
304 61
            return $this->createCommand($db)->queryColumn();
305
        }
306
307 9
        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
308 9
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
309 9
                $this->select[] = key($tables) . '.' . $this->indexBy;
310
            } else {
311
                $this->select[] = $this->indexBy;
312
            }
313
        }
314 9
        $rows = $this->createCommand($db)->queryAll();
315 9
        $results = [];
316 9
        foreach ($rows as $row) {
317 9
            $value = reset($row);
318
319 9
            if ($this->indexBy instanceof \Closure) {
320 3
                $results[call_user_func($this->indexBy, $row)] = $value;
321
            } else {
322 9
                $results[$row[$this->indexBy]] = $value;
323
            }
324
        }
325
326 9
        return $results;
327
    }
328
329
    /**
330
     * Returns the number of records.
331
     * @param string $q the COUNT expression. Defaults to '*'.
332
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
333
     * @param Connection $db the database connection used to generate the SQL statement.
334
     * If this parameter is not given (or null), the `db` application component will be used.
335
     * @return int|string number of records. The result may be a string depending on the
336
     * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
337
     */
338 87
    public function count($q = '*', $db = null)
339
    {
340 87
        if ($this->emulateExecution) {
341 6
            return 0;
342
        }
343
344 87
        return $this->queryScalar("COUNT($q)", $db);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression $this->queryScalar("COUNT({$q})", $db); of type null|string|false adds false to the return on line 344 which is incompatible with the return type declared by the interface yii\db\QueryInterface::count of type integer. It seems like you forgot to handle an error condition.
Loading history...
345
    }
346
347
    /**
348
     * Returns the sum of the specified column values.
349
     * @param string $q the column name or expression.
350
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
351
     * @param Connection $db the database connection used to generate the SQL statement.
352
     * If this parameter is not given, the `db` application component will be used.
353
     * @return mixed the sum of the specified column values.
354
     */
355 9
    public function sum($q, $db = null)
356
    {
357 9
        if ($this->emulateExecution) {
358 6
            return 0;
359
        }
360
361 3
        return $this->queryScalar("SUM($q)", $db);
362
    }
363
364
    /**
365
     * Returns the average of the specified column values.
366
     * @param string $q the column name or expression.
367
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
368
     * @param Connection $db the database connection used to generate the SQL statement.
369
     * If this parameter is not given, the `db` application component will be used.
370
     * @return mixed the average of the specified column values.
371
     */
372 9
    public function average($q, $db = null)
373
    {
374 9
        if ($this->emulateExecution) {
375 6
            return 0;
376
        }
377
378 3
        return $this->queryScalar("AVG($q)", $db);
379
    }
380
381
    /**
382
     * Returns the minimum of the specified column values.
383
     * @param string $q the column name or expression.
384
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
385
     * @param Connection $db the database connection used to generate the SQL statement.
386
     * If this parameter is not given, the `db` application component will be used.
387
     * @return mixed the minimum of the specified column values.
388
     */
389 9
    public function min($q, $db = null)
390
    {
391 9
        return $this->queryScalar("MIN($q)", $db);
392
    }
393
394
    /**
395
     * Returns the maximum of the specified column values.
396
     * @param string $q the column name or expression.
397
     * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
398
     * @param Connection $db the database connection used to generate the SQL statement.
399
     * If this parameter is not given, the `db` application component will be used.
400
     * @return mixed the maximum of the specified column values.
401
     */
402 9
    public function max($q, $db = null)
403
    {
404 9
        return $this->queryScalar("MAX($q)", $db);
405
    }
406
407
    /**
408
     * Returns a value indicating whether the query result contains any row of data.
409
     * @param Connection $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 bool whether the query result contains any row of data.
412
     */
413 73
    public function exists($db = null)
414
    {
415 73
        if ($this->emulateExecution) {
416 6
            return false;
417
        }
418 67
        $command = $this->createCommand($db);
419 67
        $params = $command->params;
420 67
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
421 67
        $command->bindValues($params);
422 67
        return (bool) $command->queryScalar();
423
    }
424
425
    /**
426
     * Queries a scalar value by setting [[select]] first.
427
     * Restores the value of select to make this query reusable.
428
     * @param string|ExpressionInterface $selectExpression
429
     * @param Connection|null $db
430
     * @return bool|string
431
     */
432 87
    protected function queryScalar($selectExpression, $db)
433
    {
434 87
        if ($this->emulateExecution) {
435 6
            return null;
436
        }
437
438
        if (
439 87
            !$this->distinct
440 87
            && empty($this->groupBy)
441 87
            && empty($this->having)
442 87
            && empty($this->union)
443
        ) {
444 86
            $select = $this->select;
445 86
            $order = $this->orderBy;
446 86
            $limit = $this->limit;
447 86
            $offset = $this->offset;
448
449 86
            $this->select = [$selectExpression];
450 86
            $this->orderBy = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $orderBy.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
451 86
            $this->limit = null;
452 86
            $this->offset = null;
453 86
            $command = $this->createCommand($db);
454
455 86
            $this->select = $select;
456 86
            $this->orderBy = $order;
457 86
            $this->limit = $limit;
458 86
            $this->offset = $offset;
459
460 86
            return $command->queryScalar();
461
        }
462
463 7
        $command = (new self())
464 7
            ->select([$selectExpression])
465 7
            ->from(['c' => $this])
466 7
            ->createCommand($db);
467 7
        $this->setCommandCache($command);
468
469 7
        return $command->queryScalar();
470
    }
471
472
    /**
473
     * Returns table names used in [[from]] indexed by aliases.
474
     * Both aliases and names are enclosed into {{ and }}.
475
     * @return string[] table names indexed by aliases
476
     * @throws \yii\base\InvalidConfigException
477
     * @since 2.0.12
478
     */
479 69
    public function getTablesUsedInFrom()
480
    {
481 69
        if (empty($this->from)) {
482
            return [];
483
        }
484
485 69
        if (is_array($this->from)) {
486 33
            $tableNames = $this->from;
487 36
        } elseif (is_string($this->from)) {
488 24
            $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
489 12
        } elseif ($this->from instanceof Expression) {
490 6
            $tableNames = [$this->from];
491
        } else {
492 6
            throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
493
        }
494
495 63
        return $this->cleanUpTableNames($tableNames);
496
    }
497
498
    /**
499
     * Clean up table names and aliases
500
     * Both aliases and names are enclosed into {{ and }}.
501
     * @param array $tableNames non-empty array
502
     * @return string[] table names indexed by aliases
503
     * @since 2.0.14
504
     */
505 165
    protected function cleanUpTableNames($tableNames)
506
    {
507 165
        $cleanedUpTableNames = [];
508 165
        foreach ($tableNames as $alias => $tableName) {
509 165
            if (is_string($tableName) && !is_string($alias)) {
510
                $pattern = <<<PATTERN
511 144
~
512
^
513
\s*
514
(
515
(?:['"`\[]|{{)
516
.*?
517
(?:['"`\]]|}})
518
|
519
\(.*?\)
520
|
521
.*?
522
)
523
(?:
524
(?:
525
    \s+
526
    (?:as)?
527
    \s*
528
)
529
(
530
   (?:['"`\[]|{{)
531
    .*?
532
    (?:['"`\]]|}})
533
    |
534
    .*?
535
)
536
)?
537
\s*
538
$
539
~iux
540
PATTERN;
541 144
                if (preg_match($pattern, $tableName, $matches)) {
542 144
                    if (isset($matches[2])) {
543 18
                        list(, $tableName, $alias) = $matches;
544
                    } else {
545 138
                        $tableName = $alias = $matches[1];
546
                    }
547
                }
548
            }
549
550
551 165
            if ($tableName instanceof Expression) {
552 12
                if (!is_string($alias)) {
553 6
                    throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
554
                }
555 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
556 153
            } elseif ($tableName instanceof self) {
557 6
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
558
            } else {
559 159
                $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
560
            }
561
        }
562
563 159
        return $cleanedUpTableNames;
564
    }
565
566
    /**
567
     * Ensures name is wrapped with {{ and }}
568
     * @param string $name
569
     * @return string
570
     */
571 159
    private function ensureNameQuoted($name)
572
    {
573 159
        $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
574 159
        if ($name && !preg_match('/^{{.*}}$/', $name)) {
575 147
            return '{{' . $name . '}}';
576
        }
577
578 30
        return $name;
579
    }
580
581
    /**
582
     * Sets the SELECT part of the query.
583
     * @param string|array|ExpressionInterface $columns the columns to be selected.
584
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
585
     * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
586
     * The method will automatically quote the column names unless a column contains some parenthesis
587
     * (which means the column contains a DB expression). A DB expression may also be passed in form of
588
     * an [[ExpressionInterface]] object.
589
     *
590
     * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
591
     * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
592
     *
593
     * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
594
     * does not need alias, do not use a string key).
595
     *
596
     * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
597
     * as a `Query` instance representing the sub-query.
598
     *
599
     * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
600
     * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
601
     * @return $this the query object itself
602
     */
603 399
    public function select($columns, $option = null)
604
    {
605 399
        if ($columns instanceof ExpressionInterface) {
606 3
            $columns = [$columns];
607 396
        } elseif (!is_array($columns)) {
608 107
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
609
        }
610 399
        $this->select = $this->getUniqueColumns($columns);
611 399
        $this->selectOption = $option;
612 399
        return $this;
613
    }
614
615
    /**
616
     * Add more columns to the SELECT part of the query.
617
     *
618
     * Note, that if [[select]] has not been specified before, you should include `*` explicitly
619
     * if you want to select all remaining columns too:
620
     *
621
     * ```php
622
     * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
623
     * ```
624
     *
625
     * @param string|array|ExpressionInterface $columns the columns to add to the select. See [[select()]] for more
626
     * details about the format of this parameter.
627
     * @return $this the query object itself
628
     * @see select()
629
     */
630 9
    public function addSelect($columns)
631
    {
632 9
        if ($columns instanceof ExpressionInterface) {
633 3
            $columns = [$columns];
634 9
        } elseif (!is_array($columns)) {
635 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
636
        }
637 9
        $columns = $this->getUniqueColumns($columns);
638 9
        if ($this->select === null) {
639 3
            $this->select = $columns;
640
        } else {
641 9
            $this->select = array_merge($this->select, $columns);
642
        }
643
644 9
        return $this;
645
    }
646
647
    /**
648
     * Returns unique column names excluding duplicates.
649
     * Columns to be removed:
650
     * - if column definition already present in SELECT part with same alias
651
     * - if column definition without alias already present in SELECT part without alias too
652
     * @param array $columns the columns to be merged to the select.
653
     * @since 2.0.14
654
     */
655 399
    protected function getUniqueColumns($columns)
656
    {
657 399
        $columns = array_unique($columns);
658 399
        $unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
659
660 399
        foreach ($columns as $columnAlias => $columnDefinition) {
661 396
            if ($columnDefinition instanceof Query) {
662 3
                continue;
663
            }
664
665
            if (
666 396
                (is_string($columnAlias) && isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition)
667 396
                || (is_integer($columnAlias) && in_array($columnDefinition, $unaliasedColumns))
668
            ) {
669 396
                unset($columns[$columnAlias]);
670
            }
671
        }
672 399
        return $columns;
673
    }
674
675
    /**
676
     * @return array List of columns without aliases from SELECT statement.
677
     * @since 2.0.14
678
     */
679 399
    protected function getUnaliasedColumnsFromSelect()
680
    {
681 399
        $result = [];
682 399
        if (is_array($this->select)) {
683 9
            foreach ($this->select as $name => $value) {
684 9
                if (is_integer($name)) {
685 9
                    $result[] = $value;
686
                }
687
            }
688
        }
689 399
        return array_unique($result);
690
    }
691
692
    /**
693
     * Sets the value indicating whether to SELECT DISTINCT or not.
694
     * @param bool $value whether to SELECT DISTINCT or not.
695
     * @return $this the query object itself
696
     */
697 6
    public function distinct($value = true)
698
    {
699 6
        $this->distinct = $value;
700 6
        return $this;
701
    }
702
703
    /**
704
     * Sets the FROM part of the query.
705
     * @param string|array|ExpressionInterface $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
706
     * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
707
     * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
708
     * The method will automatically quote the table names unless it contains some parenthesis
709
     * (which means the table is given as a sub-query or DB expression).
710
     *
711
     * When the tables are specified as an array, you may also use the array keys as the table aliases
712
     * (if a table does not need alias, do not use a string key).
713
     *
714
     * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
715
     * as the alias for the sub-query.
716
     *
717
     * To specify the `FROM` part in plain SQL, you may pass an instance of [[ExpressionInterface]].
718
     *
719
     * Here are some examples:
720
     *
721
     * ```php
722
     * // SELECT * FROM  `user` `u`, `profile`;
723
     * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
724
     *
725
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
726
     * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
727
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
728
     *
729
     * // subquery can also be a string with plain SQL wrapped in parenthesis
730
     * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
731
     * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
732
     * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
733
     * ```
734
     *
735
     * @return $this the query object itself
736
     */
737 435
    public function from($tables)
738
    {
739 435
        if ($tables instanceof Expression) {
740 6
            $tables = [$tables];
741
        }
742 435
        if (is_string($tables)) {
743 399
            $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
744
        }
745 435
        $this->from = $tables;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tables can also be of type object<yii\db\ExpressionInterface>. However, the property $from is declared as type array. 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...
746 435
        return $this;
747
    }
748
749
    /**
750
     * Sets the WHERE part of the query.
751
     *
752
     * The method requires a `$condition` parameter, and optionally a `$params` parameter
753
     * specifying the values to be bound to the query.
754
     *
755
     * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
756
     *
757
     * {@inheritdoc}
758
     *
759
     * @param string|array|ExpressionInterface $condition the conditions that should be put in the WHERE part.
760
     * @param array $params the parameters (name => value) to be bound to the query.
761
     * @return $this the query object itself
762
     * @see andWhere()
763
     * @see orWhere()
764
     * @see QueryInterface::where()
765
     */
766 744
    public function where($condition, $params = [])
767
    {
768 744
        $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\ExpressionInterface>. However, the property $where is declared as type string|array. 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...
769 744
        $this->addParams($params);
770 744
        return $this;
771
    }
772
773
    /**
774
     * Adds an additional WHERE condition to the existing one.
775
     * The new condition and the existing one will be joined using the `AND` operator.
776
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
777
     * on how to specify this parameter.
778
     * @param array $params the parameters (name => value) to be bound to the query.
779
     * @return $this the query object itself
780
     * @see where()
781
     * @see orWhere()
782
     */
783 338
    public function andWhere($condition, $params = [])
784
    {
785 338
        if ($this->where === null) {
786 286
            $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\ExpressionInterface>. However, the property $where is declared as type string|array. 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...
787 100
        } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
788 38
            $this->where[] = $condition;
789
        } else {
790 100
            $this->where = ['and', $this->where, $condition];
791
        }
792 338
        $this->addParams($params);
793 338
        return $this;
794
    }
795
796
    /**
797
     * Adds an additional WHERE condition to the existing one.
798
     * The new condition and the existing one will be joined using the `OR` operator.
799
     * @param string|array|ExpressionInterface $condition the new WHERE condition. Please refer to [[where()]]
800
     * on how to specify this parameter.
801
     * @param array $params the parameters (name => value) to be bound to the query.
802
     * @return $this the query object itself
803
     * @see where()
804
     * @see andWhere()
805
     */
806 7
    public function orWhere($condition, $params = [])
807
    {
808 7
        if ($this->where === null) {
809
            $this->where = $condition;
0 ignored issues
show
Documentation Bug introduced by
It seems like $condition can also be of type object<yii\db\ExpressionInterface>. However, the property $where is declared as type string|array. 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...
810
        } else {
811 7
            $this->where = ['or', $this->where, $condition];
812
        }
813 7
        $this->addParams($params);
814 7
        return $this;
815
    }
816
817
    /**
818
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
819
     *
820
     * It adds an additional WHERE condition for the given field and determines the comparison operator
821
     * based on the first few characters of the given value.
822
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
823
     * The new condition and the existing one will be joined using the `AND` operator.
824
     *
825
     * The comparison operator is intelligently determined based on the first few characters in the given value.
826
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
827
     *
828
     * - `<`: the column must be less than the given value.
829
     * - `>`: the column must be greater than the given value.
830
     * - `<=`: the column must be less than or equal to the given value.
831
     * - `>=`: the column must be greater than or equal to the given value.
832
     * - `<>`: the column must not be the same as the given value.
833
     * - `=`: the column must be equal to the given value.
834
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
835
     *
836
     * @param string $name the column name.
837
     * @param string $value the column value optionally prepended with the comparison operator.
838
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
839
     * Defaults to `=`, performing an exact match.
840
     * @return $this The query object itself
841
     * @since 2.0.8
842
     */
843 3
    public function andFilterCompare($name, $value, $defaultOperator = '=')
844
    {
845 3
        if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
846 3
            $operator = $matches[1];
847 3
            $value = substr($value, strlen($operator));
848
        } else {
849 3
            $operator = $defaultOperator;
850
        }
851
852 3
        return $this->andFilterWhere([$operator, $name, $value]);
853
    }
854
855
    /**
856
     * Appends a JOIN part to the query.
857
     * The first parameter specifies what type of join it is.
858
     * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
859
     * @param string|array $table the table to be joined.
860
     *
861
     * Use a string to represent the name of the table to be joined.
862
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
863
     * The method will automatically quote the table name unless it contains some parenthesis
864
     * (which means the table is given as a sub-query or DB expression).
865
     *
866
     * Use an array to represent joining with a sub-query. The array must contain only one element.
867
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
868
     * represents the alias for the sub-query.
869
     *
870
     * @param string|array $on the join condition that should appear in the ON part.
871
     * Please refer to [[where()]] on how to specify this parameter.
872
     *
873
     * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
874
     * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
875
     * match the `post.author_id` column value against the string `'user.id'`.
876
     * It is recommended to use the string syntax here which is more suited for a join:
877
     *
878
     * ```php
879
     * 'post.author_id = user.id'
880
     * ```
881
     *
882
     * @param array $params the parameters (name => value) to be bound to the query.
883
     * @return $this the query object itself
884
     */
885 48
    public function join($type, $table, $on = '', $params = [])
886
    {
887 48
        $this->join[] = [$type, $table, $on];
888 48
        return $this->addParams($params);
889
    }
890
891
    /**
892
     * Appends an INNER JOIN part to the query.
893
     * @param string|array $table the table to be joined.
894
     *
895
     * Use a string to represent the name of the table to be joined.
896
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
897
     * The method will automatically quote the table name unless it contains some parenthesis
898
     * (which means the table is given as a sub-query or DB expression).
899
     *
900
     * Use an array to represent joining with a sub-query. The array must contain only one element.
901
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
902
     * represents the alias for the sub-query.
903
     *
904
     * @param string|array $on the join condition that should appear in the ON part.
905
     * Please refer to [[join()]] on how to specify this parameter.
906
     * @param array $params the parameters (name => value) to be bound to the query.
907
     * @return $this the query object itself
908
     */
909 3
    public function innerJoin($table, $on = '', $params = [])
910
    {
911 3
        $this->join[] = ['INNER JOIN', $table, $on];
912 3
        return $this->addParams($params);
913
    }
914
915
    /**
916
     * Appends a LEFT OUTER JOIN part to the query.
917
     * @param string|array $table the table to be joined.
918
     *
919
     * Use a string to represent the name of the table to be joined.
920
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
921
     * The method will automatically quote the table name unless it contains some parenthesis
922
     * (which means the table is given as a sub-query or DB expression).
923
     *
924
     * Use an array to represent joining with a sub-query. The array must contain only one element.
925
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
926
     * represents the alias for the sub-query.
927
     *
928
     * @param string|array $on the join condition that should appear in the ON part.
929
     * Please refer to [[join()]] on how to specify this parameter.
930
     * @param array $params the parameters (name => value) to be bound to the query
931
     * @return $this the query object itself
932
     */
933 3
    public function leftJoin($table, $on = '', $params = [])
934
    {
935 3
        $this->join[] = ['LEFT JOIN', $table, $on];
936 3
        return $this->addParams($params);
937
    }
938
939
    /**
940
     * Appends a RIGHT OUTER JOIN part to the query.
941
     * @param string|array $table the table to be joined.
942
     *
943
     * Use a string to represent the name of the table to be joined.
944
     * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
945
     * The method will automatically quote the table name unless it contains some parenthesis
946
     * (which means the table is given as a sub-query or DB expression).
947
     *
948
     * Use an array to represent joining with a sub-query. The array must contain only one element.
949
     * The value must be a [[Query]] object representing the sub-query while the corresponding key
950
     * represents the alias for the sub-query.
951
     *
952
     * @param string|array $on the join condition that should appear in the ON part.
953
     * Please refer to [[join()]] on how to specify this parameter.
954
     * @param array $params the parameters (name => value) to be bound to the query
955
     * @return $this the query object itself
956
     */
957
    public function rightJoin($table, $on = '', $params = [])
958
    {
959
        $this->join[] = ['RIGHT JOIN', $table, $on];
960
        return $this->addParams($params);
961
    }
962
963
    /**
964
     * Sets the GROUP BY part of the query.
965
     * @param string|array|ExpressionInterface $columns the columns to be grouped by.
966
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
967
     * The method will automatically quote the column names unless a column contains some parenthesis
968
     * (which means the column contains a DB expression).
969
     *
970
     * Note that if your group-by is an expression containing commas, you should always use an array
971
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
972
     * the group-by columns.
973
     *
974
     * Since version 2.0.7, an [[ExpressionInterface]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
975
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
976
     * @return $this the query object itself
977
     * @see addGroupBy()
978
     */
979 24
    public function groupBy($columns)
980
    {
981 24
        if ($columns instanceof ExpressionInterface) {
982 3
            $columns = [$columns];
983 24
        } elseif (!is_array($columns)) {
984 24
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
985
        }
986 24
        $this->groupBy = $columns;
987 24
        return $this;
988
    }
989
990
    /**
991
     * Adds additional group-by columns to the existing ones.
992
     * @param string|array $columns additional columns to be grouped by.
993
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
994
     * The method will automatically quote the column names unless a column contains some parenthesis
995
     * (which means the column contains a DB expression).
996
     *
997
     * Note that if your group-by is an expression containing commas, you should always use an array
998
     * to represent the group-by information. Otherwise, the method will not be able to correctly determine
999
     * the group-by columns.
1000
     *
1001
     * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
1002
     * Since version 2.0.14, an [[ExpressionInterface]] object can be passed as well.
1003
     * @return $this the query object itself
1004
     * @see groupBy()
1005
     */
1006 3
    public function addGroupBy($columns)
1007
    {
1008 3
        if ($columns instanceof ExpressionInterface) {
1009
            $columns = [$columns];
1010 3
        } elseif (!is_array($columns)) {
1011 3
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
1012
        }
1013 3
        if ($this->groupBy === null) {
1014
            $this->groupBy = $columns;
1015
        } else {
1016 3
            $this->groupBy = array_merge($this->groupBy, $columns);
1017
        }
1018
1019 3
        return $this;
1020
    }
1021
1022
    /**
1023
     * Sets the HAVING part of the query.
1024
     * @param string|array|ExpressionInterface $condition the conditions to be put after HAVING.
1025
     * Please refer to [[where()]] on how to specify this parameter.
1026
     * @param array $params the parameters (name => value) to be bound to the query.
1027
     * @return $this the query object itself
1028
     * @see andHaving()
1029
     * @see orHaving()
1030
     */
1031 10
    public function having($condition, $params = [])
1032
    {
1033 10
        $this->having = $condition;
1034 10
        $this->addParams($params);
1035 10
        return $this;
1036
    }
1037
1038
    /**
1039
     * Adds an additional HAVING condition to the existing one.
1040
     * The new condition and the existing one will be joined using the `AND` operator.
1041
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1042
     * on how to specify this parameter.
1043
     * @param array $params the parameters (name => value) to be bound to the query.
1044
     * @return $this the query object itself
1045
     * @see having()
1046
     * @see orHaving()
1047
     */
1048 3
    public function andHaving($condition, $params = [])
1049
    {
1050 3
        if ($this->having === null) {
1051
            $this->having = $condition;
1052
        } else {
1053 3
            $this->having = ['and', $this->having, $condition];
1054
        }
1055 3
        $this->addParams($params);
1056 3
        return $this;
1057
    }
1058
1059
    /**
1060
     * Adds an additional HAVING condition to the existing one.
1061
     * The new condition and the existing one will be joined using the `OR` operator.
1062
     * @param string|array|ExpressionInterface $condition the new HAVING condition. Please refer to [[where()]]
1063
     * on how to specify this parameter.
1064
     * @param array $params the parameters (name => value) to be bound to the query.
1065
     * @return $this the query object itself
1066
     * @see having()
1067
     * @see andHaving()
1068
     */
1069 3
    public function orHaving($condition, $params = [])
1070
    {
1071 3
        if ($this->having === null) {
1072
            $this->having = $condition;
1073
        } else {
1074 3
            $this->having = ['or', $this->having, $condition];
1075
        }
1076 3
        $this->addParams($params);
1077 3
        return $this;
1078
    }
1079
1080
    /**
1081
     * Sets the HAVING part of the query but ignores [[isEmpty()|empty operands]].
1082
     *
1083
     * This method is similar to [[having()]]. The main difference is that this method will
1084
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1085
     * for building query conditions based on filter values entered by users.
1086
     *
1087
     * The following code shows the difference between this method and [[having()]]:
1088
     *
1089
     * ```php
1090
     * // HAVING `age`=:age
1091
     * $query->filterHaving(['name' => null, 'age' => 20]);
1092
     * // HAVING `age`=:age
1093
     * $query->having(['age' => 20]);
1094
     * // HAVING `name` IS NULL AND `age`=:age
1095
     * $query->having(['name' => null, 'age' => 20]);
1096
     * ```
1097
     *
1098
     * Note that unlike [[having()]], you cannot pass binding parameters to this method.
1099
     *
1100
     * @param array $condition the conditions that should be put in the HAVING part.
1101
     * See [[having()]] on how to specify this parameter.
1102
     * @return $this the query object itself
1103
     * @see having()
1104
     * @see andFilterHaving()
1105
     * @see orFilterHaving()
1106
     * @since 2.0.11
1107
     */
1108 6
    public function filterHaving(array $condition)
1109
    {
1110 6
        $condition = $this->filterCondition($condition);
1111 6
        if ($condition !== []) {
1112 6
            $this->having($condition);
1113
        }
1114
1115 6
        return $this;
1116
    }
1117
1118
    /**
1119
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1120
     * The new condition and the existing one will be joined using the `AND` operator.
1121
     *
1122
     * This method is similar to [[andHaving()]]. The main difference is that this method will
1123
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1124
     * for building query conditions based on filter values entered by users.
1125
     *
1126
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1127
     * on how to specify this parameter.
1128
     * @return $this the query object itself
1129
     * @see filterHaving()
1130
     * @see orFilterHaving()
1131
     * @since 2.0.11
1132
     */
1133 6
    public function andFilterHaving(array $condition)
1134
    {
1135 6
        $condition = $this->filterCondition($condition);
1136 6
        if ($condition !== []) {
1137
            $this->andHaving($condition);
1138
        }
1139
1140 6
        return $this;
1141
    }
1142
1143
    /**
1144
     * Adds an additional HAVING condition to the existing one but ignores [[isEmpty()|empty operands]].
1145
     * The new condition and the existing one will be joined using the `OR` operator.
1146
     *
1147
     * This method is similar to [[orHaving()]]. The main difference is that this method will
1148
     * remove [[isEmpty()|empty query operands]]. As a result, this method is best suited
1149
     * for building query conditions based on filter values entered by users.
1150
     *
1151
     * @param array $condition the new HAVING condition. Please refer to [[having()]]
1152
     * on how to specify this parameter.
1153
     * @return $this the query object itself
1154
     * @see filterHaving()
1155
     * @see andFilterHaving()
1156
     * @since 2.0.11
1157
     */
1158 6
    public function orFilterHaving(array $condition)
1159
    {
1160 6
        $condition = $this->filterCondition($condition);
1161 6
        if ($condition !== []) {
1162
            $this->orHaving($condition);
1163
        }
1164
1165 6
        return $this;
1166
    }
1167
1168
    /**
1169
     * Appends a SQL statement using UNION operator.
1170
     * @param string|Query $sql the SQL statement to be appended using UNION
1171
     * @param bool $all TRUE if using UNION ALL and FALSE if using UNION
1172
     * @return $this the query object itself
1173
     */
1174 10
    public function union($sql, $all = false)
1175
    {
1176 10
        $this->union[] = ['query' => $sql, 'all' => $all];
1177 10
        return $this;
1178
    }
1179
1180
    /**
1181
     * Sets the parameters to be bound to the query.
1182
     * @param array $params list of query parameter values indexed by parameter placeholders.
1183
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1184
     * @return $this the query object itself
1185
     * @see addParams()
1186
     */
1187 6
    public function params($params)
1188
    {
1189 6
        $this->params = $params;
1190 6
        return $this;
1191
    }
1192
1193
    /**
1194
     * Adds additional parameters to be bound to the query.
1195
     * @param array $params list of query parameter values indexed by parameter placeholders.
1196
     * For example, `[':name' => 'Dan', ':age' => 31]`.
1197
     * @return $this the query object itself
1198
     * @see params()
1199
     */
1200 998
    public function addParams($params)
1201
    {
1202 998
        if (!empty($params)) {
1203 74
            if (empty($this->params)) {
1204 74
                $this->params = $params;
1205
            } else {
1206 6
                foreach ($params as $name => $value) {
1207 6
                    if (is_int($name)) {
1208
                        $this->params[] = $value;
1209
                    } else {
1210 6
                        $this->params[$name] = $value;
1211
                    }
1212
                }
1213
            }
1214
        }
1215
1216 998
        return $this;
1217
    }
1218
1219
    /**
1220
     * Enables query cache for this Query.
1221
     * @param int|true the number of seconds that query results can remain valid in cache.
1222
     * Use 0 to indicate that the cached data will never expire.
1223
     * Use a negative number to indicate that query cache should not be used.
1224
     * Use boolean `true` to indicate that [[Connection::queryCacheDuration]] should be used.
1225
     * Defaults to `true`.
1226
     * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached result.
1227
     * @return $this the Query object itself
1228
     */
1229 3
    public function cache($duration = true, $dependency = null)
1230
    {
1231 3
        $this->queryCacheDuration = $duration;
0 ignored issues
show
Documentation Bug introduced by
It seems like $duration of type boolean is incompatible with the declared type integer|object<yii\db\true> of property $queryCacheDuration.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1232 3
        $this->queryCacheDependency = $dependency;
1233 3
        return $this;
1234
    }
1235
1236
    /**
1237
     * Disables query cache for this Query.
1238
     * @return $this the Query object itself
1239
     * @since 2.0.14
1240
     */
1241 3
    public function noCache()
1242
    {
1243 3
        $this->queryCacheDuration = -1;
1244 3
        return $this;
1245
    }
1246
1247
    /**
1248
     * Sets $command cache, if this query has enabled caching.
1249
     *
1250
     * @param Command $command
1251
     * @return Command
1252
     * @since 2.0.14
1253
     */
1254 744
    protected function setCommandCache($command)
1255
    {
1256 744
        if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
1257 3
            $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
1258 3
            $command->cache($duration, $this->queryCacheDependency);
1259
        }
1260
1261 744
        return $command;
1262
    }
1263
1264
    /**
1265
     * Creates a new Query object and copies its property values from an existing one.
1266
     * The properties being copies are the ones to be used by query builders.
1267
     * @param Query $from the source query object
1268
     * @return Query the new Query object
1269
     */
1270 384
    public static function create($from)
1271
    {
1272 384
        return new self([
1273 384
            'where' => $from->where,
1274 384
            'limit' => $from->limit,
1275 384
            'offset' => $from->offset,
1276 384
            'orderBy' => $from->orderBy,
1277 384
            'indexBy' => $from->indexBy,
1278 384
            'select' => $from->select,
1279 384
            'selectOption' => $from->selectOption,
1280 384
            'distinct' => $from->distinct,
1281 384
            'from' => $from->from,
1282 384
            'groupBy' => $from->groupBy,
1283 384
            'join' => $from->join,
1284 384
            'having' => $from->having,
1285 384
            'union' => $from->union,
1286 384
            'params' => $from->params,
1287
        ]);
1288
    }
1289
1290
    /**
1291
     * Returns the SQL representation of Query
1292
     * @return string
1293
     */
1294
    public function __toString()
1295
    {
1296
        return serialize($this);
1297
    }
1298
}
1299