Completed
Push — query-alias ( e06046...9802bc )
by Carsten
40:39
created

ActiveQuery::alias()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 20
ccs 7
cts 7
cp 1
rs 8.8571
cc 5
eloc 13
nc 2
nop 1
crap 5
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\base\InvalidConfigException;
11
12
/**
13
 * ActiveQuery represents a DB query associated with an Active Record class.
14
 *
15
 * An ActiveQuery can be a normal query or be used in a relational context.
16
 *
17
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
18
 * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
19
 *
20
 * Normal Query
21
 * ------------
22
 *
23
 * ActiveQuery mainly provides the following methods to retrieve the query results:
24
 *
25
 * - [[one()]]: returns a single record populated with the first row of data.
26
 * - [[all()]]: returns all records based on the query results.
27
 * - [[count()]]: returns the number of records.
28
 * - [[sum()]]: returns the sum over the specified column.
29
 * - [[average()]]: returns the average over the specified column.
30
 * - [[min()]]: returns the min over the specified column.
31
 * - [[max()]]: returns the max over the specified column.
32
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
33
 * - [[column()]]: returns the value of the first column in the query result.
34
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
35
 *
36
 * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
37
 * [[orderBy()]] to customize the query options.
38
 *
39
 * ActiveQuery also provides the following additional query options:
40
 *
41
 * - [[with()]]: list of relations that this query should be performed with.
42
 * - [[joinWith()]]: reuse a relation query definition to add a join to a query.
43
 * - [[indexBy()]]: the name of the column by which the query result should be indexed.
44
 * - [[asArray()]]: whether to return each record as an array.
45
 *
46
 * These options can be configured using methods of the same name. For example:
47
 *
48
 * ```php
49
 * $customers = Customer::find()->with('orders')->asArray()->all();
50
 * ```
51
 *
52
 * Relational query
53
 * ----------------
54
 *
55
 * In relational context ActiveQuery represents a relation between two Active Record classes.
56
 *
57
 * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and
58
 * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
59
 * a getter method which calls one of the above methods and returns the created ActiveQuery object.
60
 *
61
 * A relation is specified by [[link]] which represents the association between columns
62
 * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
63
 *
64
 * If a relation involves a junction table, it may be specified by [[via()]] or [[viaTable()]] method.
65
 * These methods may only be called in a relational context. Same is true for [[inverseOf()]], which
66
 * marks a relation as inverse of another relation and [[onCondition()]] which adds a condition that
67
 * is to be added to relational query join condition.
68
 *
69
 * @author Qiang Xue <[email protected]>
70
 * @author Carsten Brandt <[email protected]>
71
 * @since 2.0
72
 */
73
class ActiveQuery extends Query implements ActiveQueryInterface
74
{
75
    use ActiveQueryTrait;
76
    use ActiveRelationTrait;
77
78
    /**
79
     * @event Event an event that is triggered when the query is initialized via [[init()]].
80
     */
81
    const EVENT_INIT = 'init';
82
83
    /**
84
     * @var string the SQL statement to be executed for retrieving AR records.
85
     * This is set by [[ActiveRecord::findBySql()]].
86
     */
87
    public $sql;
88
    /**
89
     * @var string|array the join condition to be used when this query is used in a relational context.
90
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
91
     * Otherwise, the condition will be used in the WHERE part of a query.
92
     * Please refer to [[Query::where()]] on how to specify this parameter.
93
     * @see onCondition()
94
     */
95
    public $on;
96
    /**
97
     * @var array a list of relations that this query should be joined with
98
     */
99
    public $joinWith;
100
101
102
    /**
103
     * Constructor.
104
     * @param string $modelClass the model class associated with this query
105
     * @param array $config configurations to be applied to the newly created query object
106
     */
107 237
    public function __construct($modelClass, $config = [])
108
    {
109 237
        $this->modelClass = $modelClass;
110 237
        parent::__construct($config);
111 237
    }
112
113
    /**
114
     * Initializes the object.
115
     * This method is called at the end of the constructor. The default implementation will trigger
116
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
117
     * to ensure triggering of the event.
118
     */
119 237
    public function init()
120
    {
121 237
        parent::init();
122 237
        $this->trigger(self::EVENT_INIT);
123 237
    }
124
125
    /**
126
     * Executes query and returns all results as an array.
127
     * @param Connection $db the DB connection used to create the DB command.
128
     * If null, the DB connection returned by [[modelClass]] will be used.
129
     * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
130
     */
131 144
    public function all($db = null)
132
    {
133 144
        return parent::all($db);
134
    }
135
136
    /**
137
     * @inheritdoc
138
     */
139 226
    public function prepare($builder)
140
    {
141
        // NOTE: because the same ActiveQuery may be used to build different SQL statements
142
        // (e.g. by ActiveDataProvider, one for count query, the other for row data query,
143
        // it is important to make sure the same ActiveQuery can be used to build SQL statements
144
        // multiple times.
145 226
        if (!empty($this->joinWith)) {
146 21
            $this->buildJoinWith();
147 21
            $this->joinWith = null;    // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $joinWith.

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...
148 21
        }
149
150 226
        if (empty($this->from)) {
151
            /* @var $modelClass ActiveRecord */
152 226
            $modelClass = $this->modelClass;
153 226
            $tableName = $modelClass::tableName();
154 226
            $this->from = [$tableName];
155 226
        }
156
157 226
        if (empty($this->select) && !empty($this->join)) {
158 18
            list(, $alias) = $this->getQueryTableName($this);
159 18
            $this->select = ["$alias.*"];
160 18
        }
161
162 226
        if ($this->primaryModel === null) {
163
            // eager loading
164 226
            $query = Query::create($this);
165 226
        } else {
166
            // lazy loading of a relation
167 60
            $where = $this->where;
168
169 60
            if ($this->via instanceof self) {
170
                // via junction table
171 12
                $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
172 12
                $this->filterByModels($viaModels);
173 60
            } elseif (is_array($this->via)) {
174
                // via relation
175
                /* @var $viaQuery ActiveQuery */
176 27
                list($viaName, $viaQuery) = $this->via;
177 27
                if ($viaQuery->multiple) {
178 27
                    $viaModels = $viaQuery->all();
179 27
                    $this->primaryModel->populateRelation($viaName, $viaModels);
180 27
                } else {
181
                    $model = $viaQuery->one();
182
                    $this->primaryModel->populateRelation($viaName, $model);
183
                    $viaModels = $model === null ? [] : [$model];
184
                }
185 27
                $this->filterByModels($viaModels);
186 27
            } else {
187 54
                $this->filterByModels([$this->primaryModel]);
188
            }
189
190 60
            $query = Query::create($this);
191 60
            $this->where = $where;
192
        }
193
194 226
        if (!empty($this->on)) {
195 15
            $query->andWhere($this->on);
196 15
        }
197
198 226
        return $query;
199
    }
200
201
    /**
202
     * @inheritdoc
203
     */
204 200
    public function populate($rows)
205
    {
206 200
        if (empty($rows)) {
207 35
            return [];
208
        }
209
210 200
        $models = $this->createModels($rows);
211 200
        if (!empty($this->join) && $this->indexBy === null) {
212 21
            $models = $this->removeDuplicatedModels($models);
213 21
        }
214 200
        if (!empty($this->with)) {
215 49
            $this->findWith($this->with, $models);
216 49
        }
217 200
        if (!$this->asArray) {
218 194
            foreach ($models as $model) {
219 194
                $model->afterFind();
220 194
            }
221 194
        }
222
223 200
        return $models;
224
    }
225
226
    /**
227
     * Removes duplicated models by checking their primary key values.
228
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
229
     * @param array $models the models to be checked
230
     * @throws InvalidConfigException if model primary key is empty
231
     * @return array the distinctive models
232
     */
233 21
    private function removeDuplicatedModels($models)
234
    {
235 21
        $hash = [];
236
        /* @var $class ActiveRecord */
237 21
        $class = $this->modelClass;
238 21
        $pks = $class::primaryKey();
239
240 21
        if (count($pks) > 1) {
241
            // composite primary key
242 3
            foreach ($models as $i => $model) {
243 3
                $key = [];
244 3
                foreach ($pks as $pk) {
245 3
                    if (!isset($model[$pk])) {
246
                        // do not continue if the primary key is not part of the result set
247 3
                        break 2;
248
                    }
249 3
                    $key[] = $model[$pk];
250 3
                }
251
                $key = serialize($key);
252
                if (isset($hash[$key])) {
253
                    unset($models[$i]);
254
                } else {
255
                    $hash[$key] = true;
256
                }
257 3
            }
258 21
        } elseif (empty($pks)) {
259
            throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
260
        } else {
261
            // single column primary key
262 21
            $pk = reset($pks);
263 21
            foreach ($models as $i => $model) {
264 21
                if (!isset($model[$pk])) {
265
                    // do not continue if the primary key is not part of the result set
266 3
                    break;
267
                }
268 18
                $key = $model[$pk];
269 18
                if (isset($hash[$key])) {
270 15
                    unset($models[$i]);
271 18
                } elseif ($key !== null) {
272 18
                    $hash[$key] = true;
273 18
                }
274 21
            }
275
        }
276
277 21
        return array_values($models);
278
    }
279
280
    /**
281
     * Executes query and returns a single row of result.
282
     * @param Connection $db the DB connection used to create the DB command.
283
     * If null, the DB connection returned by [[modelClass]] will be used.
284
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
285
     * the query result may be either an array or an ActiveRecord object. Null will be returned
286
     * if the query results in nothing.
287
     */
288 159
    public function one($db = null)
289
    {
290 159
        $row = parent::one($db);
291 159
        if ($row !== false) {
292 159
            $models = $this->populate([$row]);
293 159
            return reset($models) ?: null;
294
        } else {
295 21
            return null;
296
        }
297
    }
298
299
    /**
300
     * Creates a DB command that can be used to execute this query.
301
     * @param Connection $db the DB connection used to create the DB command.
302
     * If null, the DB connection returned by [[modelClass]] will be used.
303
     * @return Command the created DB command instance.
304
     */
305 229
    public function createCommand($db = null)
306
    {
307
        /* @var $modelClass ActiveRecord */
308 229
        $modelClass = $this->modelClass;
309 229
        if ($db === null) {
310 227
            $db = $modelClass::getDb();
311 227
        }
312
313 229
        if ($this->sql === null) {
314 226
            list ($sql, $params) = $db->getQueryBuilder()->build($this);
315 226
        } else {
316 3
            $sql = $this->sql;
317 3
            $params = $this->params;
318
        }
319
320 229
        return $db->createCommand($sql, $params);
321
    }
322
323
    /**
324
     * @inheritdoc
325
     */
326 55
    protected function queryScalar($selectExpression, $db)
327
    {
328 55
        if ($this->sql === null) {
329 52
            return parent::queryScalar($selectExpression, $db);
330
        }
331
        /* @var $modelClass ActiveRecord */
332 3
        $modelClass = $this->modelClass;
333 3
        if ($db === null) {
334 3
            $db = $modelClass::getDb();
335 3
        }
336 3
        return (new Query)->select([$selectExpression])
337 3
            ->from(['c' => "({$this->sql})"])
338 3
            ->params($this->params)
339 3
            ->createCommand($db)
340 3
            ->queryScalar();
341
    }
342
343
    /**
344
     * Joins with the specified relations.
345
     *
346
     * This method allows you to reuse existing relation definitions to perform JOIN queries.
347
     * Based on the definition of the specified relation(s), the method will append one or multiple
348
     * JOIN statements to the current query.
349
     *
350
     * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
351
     * which is equivalent to calling [[with()]] using the specified relations.
352
     *
353
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
354
     * You may specify the table names manually or use the table alias syntax described in the [Guide about alias handling](db-querybuilder#aliases)
355
     * for this.
356
     *
357
     * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
358
     * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
359
     *
360
     * @param string|array $with the relations to be joined. Each array element represents a single relation.
361
     * The array keys are relation names, and the array values are the corresponding anonymous functions that
362
     * can be used to modify the relation queries on-the-fly. If a relation query does not need modification,
363
     * you may use the relation name as the array value. Sub-relations can also be specified (see [[with()]]).
364
     * For example,
365
     *
366
     * ```php
367
     * // find all orders that contain books, and eager loading "books"
368
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
369
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
370
     * Order::find()->joinWith([
371
     *     'books' => function (\yii\db\ActiveQuery $query) {
372
     *         $query->orderBy('item.name');
373
     *     }
374
     * ])->all();
375
     * ```
376
     *
377
     * @param boolean|array $eagerLoading whether to eager load the relations specified in `$with`.
378
     * When this is a boolean, it applies to all relations specified in `$with`. Use an array
379
     * to explicitly list which relations in `$with` need to be eagerly loaded. Defaults to `true`.
380
     * @param string|array $joinType the join type of the relations specified in `$with`.
381
     * When this is a string, it applies to all relations specified in `$with`. Use an array
382
     * in the format of `relationName => joinType` to specify different join types for different relations.
383
     * @return $this the query object itself
384
     */
385
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
386
    {
387
        $this->joinWith[] = [(array) $with, $eagerLoading, $joinType];
388
389
        return $this;
390
    }
391
392
    private function buildJoinWith()
393
    {
394
        $join = $this->join;
395
        $this->join = [];
396
397 21
        $model = new $this->modelClass;
398
        foreach ($this->joinWith as $config) {
399 21
            list ($with, $eagerLoading, $joinType) = $config;
400 21
            $this->joinWithRelations($model, $with, $joinType);
401 21
402 21
            if (is_array($eagerLoading)) {
403 21
                foreach ($with as $name => $callback) {
404 21
                    if (is_int($name)) {
405
                        if (!in_array($callback, $eagerLoading, true)) {
406 21
                            unset($with[$name]);
407
                        }
408 12
                    } elseif (!in_array($name, $eagerLoading, true)) {
409 12
                        unset($with[$name]);
410 12
                    }
411
                }
412 12
            } elseif (!$eagerLoading) {
413 12
                $with = [];
414 12
            }
415 12
416 12
            $this->with($with);
417 12
        }
418
419 21
        // remove duplicated joins added by joinWithRelations that may be added
420 21
        // e.g. when joining a relation and a via relation at the same time
421 21
        $uniqueJoins = [];
422 18
        foreach ($this->join as $j) {
423
            $uniqueJoins[serialize($j)] = $j;
424 21
        }
425 21
        $this->join = array_values($uniqueJoins);
426 21
427
        if (!empty($join)) {
428
            // append explicit join to joinWith()
429 21
            // https://github.com/yiisoft/yii2/issues/2880
430
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
431 21
        }
432 21
    }
433
434 21
    /**
435 21
     * Inner joins with the specified relations.
436 21
     * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
437 21
     * Please refer to [[joinWith()]] for detailed usage of this method.
438
     * @param string|array $with the relations to be joined with.
439 21
     * @param boolean|array $eagerLoading whether to eager loading the relations.
440
     * @return $this the query object itself
441
     * @see joinWith()
442
     */
443
    public function innerJoinWith($with, $eagerLoading = true)
444
    {
445
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
446
    }
447
448
    /**
449 21
     * Modifies the current query by adding join fragments based on the given relations.
450 15
     * @param ActiveRecord $model the primary model
451 15
     * @param array $with the relations to be joined
452
     * @param string|array $joinType the join type
453 21
     */
454 21
    private function joinWithRelations($model, $with, $joinType)
455
    {
456
        $relations = [];
457
458 21
        foreach ($with as $name => $callback) {
459 21
            if (is_int($name)) {
460 21
                $name = $callback;
461 21
                $callback = null;
462 21
            }
463
464 21
            $primaryModel = $model;
465
            $parent = $this;
466
            $prefix = '';
467
            while (($pos = strpos($name, '.')) !== false) {
468
                $childName = substr($name, $pos + 1);
469 21
                $name = substr($name, 0, $pos);
470
                $fullName = $prefix === '' ? $name : "$prefix.$name";
471
                if (!isset($relations[$fullName])) {
472
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
473
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
474
                } else {
475
                    $relation = $relations[$fullName];
476
                }
477
                $primaryModel = new $relation->modelClass;
478
                $parent = $relation;
479
                $prefix = $fullName;
480 12
                $name = $childName;
481
            }
482 12
483
            $fullName = $prefix === '' ? $name : "$prefix.$name";
484
            if (!isset($relations[$fullName])) {
485
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
486
                if ($callback !== null) {
487
                    call_user_func($callback, $relation);
488
                }
489
                if (!empty($relation->joinWith)) {
490
                    $relation->buildJoinWith();
491 21
                }
492
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
493 21
            }
494
        }
495 21
    }
496 21
497 21
    /**
498 21
     * Returns the join type based on the given join type parameter and the relation name.
499 21
     * @param string|array $joinType the given join type(s)
500
     * @param string $name relation name
501 21
     * @return string the real join type
502 21
     */
503 21
    private function getJoinType($joinType, $name)
504 21
    {
505 9
        if (is_array($joinType) && isset($joinType[$name])) {
506 9
            return $joinType[$name];
507 9
        } else {
508 9
            return is_string($joinType) ? $joinType : 'INNER JOIN';
509
        }
510
    }
511
512 9
    /**
513
     * Returns the table name and the table alias for [[modelClass]].
514 9
     * @param ActiveQuery $query
515 9
     * @return array the table name and the table alias.
516 9
     */
517 9
    private function getQueryTableName($query)
518 9
    {
519
        if (empty($query->from)) {
520 21
            /* @var $modelClass ActiveRecord */
521 21
            $modelClass = $query->modelClass;
522 21
            $tableName = $modelClass::tableName();
523 21
        } else {
524 18
            $tableName = '';
525 18
            foreach ($query->from as $alias => $tableName) {
526 21
                if (is_string($alias)) {
527 9
                    return [$tableName, $alias];
528 9
                } else {
529 21
                    break;
530 21
                }
531 21
            }
532 21
        }
533
534
        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
535
            $alias = $matches[2];
536
        } else {
537
            $alias = $tableName;
538
        }
539
540 21
        return [$tableName, $alias];
541
    }
542 21
543
    /**
544
     * Joins a parent query with a child query.
545 21
     * The current query object will be modified accordingly.
546
     * @param ActiveQuery $parent
547
     * @param ActiveQuery $child
548
     * @param string $joinType
549
     */
550
    private function joinWithRelation($parent, $child, $joinType)
551
    {
552
        $via = $child->via;
553
        $child->via = null;
554 24
        if ($via instanceof ActiveQuery) {
555
            // via table
556 24
            $this->joinWithRelation($parent, $via, $joinType);
557
            $this->joinWithRelation($via, $child, $joinType);
558 24
            return;
559 24
        } elseif (is_array($via)) {
560 24
            // via relation
561 21
            $this->joinWithRelation($parent, $via[1], $joinType);
562 21
            $this->joinWithRelation($via[1], $child, $joinType);
563 21
            return;
564 15
        }
565
566 18
        list ($parentTable, $parentAlias) = $this->getQueryTableName($parent);
0 ignored issues
show
Unused Code introduced by
The assignment to $parentTable is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
567
        list ($childTable, $childAlias) = $this->getQueryTableName($child);
568 18
569
        if (!empty($child->link)) {
570
571 24
            if (strpos($parentAlias, '{{') === false) {
572 3
                $parentAlias = '{{' . $parentAlias . '}}';
573 3
            }
574 24
            if (strpos($childAlias, '{{') === false) {
575
                $childAlias = '{{' . $childAlias . '}}';
576
            }
577 24
578
            $on = [];
579
            foreach ($child->link as $childColumn => $parentColumn) {
580
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
581
            }
582
            $on = implode(' AND ', $on);
583
            if (!empty($child->on)) {
584
                $on = ['and', $on, $child->on];
585
            }
586
        } else {
587 21
            $on = $child->on;
588
        }
589 21
        $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
590 21
591 21
        if (!empty($child->where)) {
592
            $this->andWhere($child->where);
593 12
        }
594 12
        if (!empty($child->having)) {
595 12
            $this->andHaving($child->having);
596 21
        }
597
        if (!empty($child->orderBy)) {
598 15
            $this->addOrderBy($child->orderBy);
599 15
        }
600 15
        if (!empty($child->groupBy)) {
601
            $this->addGroupBy($child->groupBy);
602
        }
603 21
        if (!empty($child->params)) {
604 21
            $this->addParams($child->params);
605
        }
606 21
        if (!empty($child->join)) {
607
            foreach ($child->join as $join) {
608 21
                $this->join[] = $join;
609 21
            }
610 21
        }
611 21
        if (!empty($child->union)) {
612 21
            foreach ($child->union as $union) {
613 21
                $this->union[] = $union;
614
            }
615 21
        }
616 21
    }
617 21
618 21
    /**
619 21
     * Sets the ON condition for a relational query.
620 21
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
621 12
     * Otherwise, the condition will be used in the WHERE part of a query.
622 12
     *
623 21
     * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
624
     *
625
     * ```php
626 21
     * public function getActiveUsers()
627
     * {
628 21
     *     return $this->hasMany(User::className(), ['id' => 'user_id'])
629 9
     *                 ->onCondition(['active' => true]);
630 9
     * }
631 21
     * ```
632
     *
633
     * Note that this condition is applied in case of a join as well as when fetching the related records.
634 21
     * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
635 15
     * record will cause an error in a non-join-query.
636 15
     *
637 21
     * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
638
     * @param array $params the parameters (name => value) to be bound to the query.
639
     * @return $this the query object itself
640 21
     */
641
    public function onCondition($condition, $params = [])
642
    {
643 21
        $this->on = $condition;
644 9
        $this->addParams($params);
645 9
        return $this;
646 9
    }
647 9
648 9
    /**
649 21
     * Adds an additional ON condition to the existing one.
650
     * The new condition and the existing one will be joined using the 'AND' operator.
651
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
652
     * on how to specify this parameter.
653
     * @param array $params the parameters (name => value) to be bound to the query.
654 21
     * @return $this the query object itself
655
     * @see onCondition()
656
     * @see orOnCondition()
657
     */
658
    public function andOnCondition($condition, $params = [])
659
    {
660
        if ($this->on === null) {
661
            $this->on = $condition;
662
        } else {
663
            $this->on = ['and', $this->on, $condition];
664
        }
665
        $this->addParams($params);
666
        return $this;
667
    }
668
669
    /**
670
     * Adds an additional ON condition to the existing one.
671
     * The new condition and the existing one will be joined using the 'OR' operator.
672
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
673
     * on how to specify this parameter.
674
     * @param array $params the parameters (name => value) to be bound to the query.
675
     * @return $this the query object itself
676
     * @see onCondition()
677
     * @see andOnCondition()
678
     */
679 15
    public function orOnCondition($condition, $params = [])
680
    {
681 15
        if ($this->on === null) {
682 15
            $this->on = $condition;
683 15
        } else {
684
            $this->on = ['or', $this->on, $condition];
685
        }
686
        $this->addParams($params);
687
        return $this;
688
    }
689
690
    /**
691
     * Specifies the junction table for a relational query.
692
     *
693
     * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
694
     *
695
     * ```php
696
     * public function getItems()
697
     * {
698
     *     return $this->hasMany(Item::className(), ['id' => 'item_id'])
699
     *                 ->viaTable('order_item', ['order_id' => 'id']);
700
     * }
701
     * ```
702
     *
703
     * @param string $tableName the name of the junction table.
704
     * @param array $link the link between the junction table and the table associated with [[primaryModel]].
705
     * The keys of the array represent the columns in the junction table, and the values represent the columns
706
     * in the [[primaryModel]] table.
707
     * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
708
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
709
     * @return $this the query object itself
710
     * @see via()
711
     */
712
    public function viaTable($tableName, $link, callable $callable = null)
713
    {
714
        $relation = new ActiveQuery(get_class($this->primaryModel), [
715
            'from' => [$tableName],
716
            'link' => $link,
717
            'multiple' => true,
718
            'asArray' => true,
719
        ]);
720
        $this->via = $relation;
721
        if ($callable !== null) {
722
            call_user_func($callable, $relation);
723
        }
724
725
        return $this;
726
    }
727
728
    /**
729
     * Define an alias for the table defined in [[modelClass]].
730
     *
731
     * This method will adjust [[from]] so that an already defined alias will be overwritten.
732
     * If none was defined, [[from]] will be populated with the given alias.
733
     *
734
     * @param string $alias the table alias.
735
     * @return $this the query object itself
736
     * @since 2.0.7
737
     */
738
    public function alias($alias)
739
    {
740
        if (empty($this->from) || count($this->from) < 2) {
741
            list($tableName, ) = $this->getQueryTableName($this);
742
            $this->from = [$alias => $tableName];
743
        } else {
744
            /* @var $modelClass ActiveRecord */
745
            $modelClass = $this->modelClass;
746
            $tableName = $modelClass::tableName();
747
748
            foreach ($this->from as $key => $table) {
749
                if ($table === $tableName) {
750 21
                    unset($this->from[$key]);
751
                    $this->from[$alias] = $tableName;
752 21
                }
753 21
            }
754 21
        }
755 21
        $this->populateAliases($this->from);
756 21
        return $this;
757 21
    }
758
}
759