Completed
Push — query-filter-having ( 837b33 )
by Alexander
12:09 queued 03:23
created

Query::filterHaving()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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