Completed
Pull Request — query-alias (#10817)
by Carsten
37:41 queued 34:17
created

ActiveQuery::joinWith()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 31
ccs 24
cts 24
cp 1
rs 8.439
cc 6
eloc 19
nc 9
nop 3
crap 6
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. This can either be a string, representing a relation name or
361
     * an array with the following semantics:
362
     *
363
     * - Each array element represents a single relation.
364
     * - You may specify the relation name as the array key and provide an anonymous functions that
365
     *   can be used to modify the relation queries on-the-fly as the array value.
366
     * - If a relation query does not need modification, you may use the relation name as the array value.
367
     *
368
     * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
369
     *
370
     * Sub-relations can also be specified, see [[with()]] for the syntax.
371
     *
372
     * In the following you find some examples:
373
     *
374
     * ```php
375
     * // find all orders that contain books, and eager loading "books"
376
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
377
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
378
     * Order::find()->joinWith([
379
     *     'books' => function (\yii\db\ActiveQuery $query) {
380
     *         $query->orderBy('item.name');
381
     *     }
382
     * ])->all();
383
     * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
384
     * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
385
     * ```
386
     *
387
     * The alias syntax is available since version 2.0.7.
388
     *
389
     * @param boolean|array $eagerLoading whether to eager load the relations specified in `$with`.
390
     * When this is a boolean, it applies to all relations specified in `$with`. Use an array
391
     * to explicitly list which relations in `$with` need to be eagerly loaded. Defaults to `true`.
392
     * @param string|array $joinType the join type of the relations specified in `$with`.
393
     * When this is a string, it applies to all relations specified in `$with`. Use an array
394
     * in the format of `relationName => joinType` to specify different join types for different relations.
395
     * @return $this the query object itself
396
     */
397 21
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
398
    {
399 21
        $relations = [];
400 21
        foreach((array) $with as $name => $callback) {
401 21
            if (is_int($name)) {
402 21
                $name = $callback;
403 21
                $callback = null;
404 21
            }
405
406 21
            if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
407
                // relation is defined with an alias, adjust callback to apply alias
408 12
                list(, $relation, $alias) = $matches;
409 12
                $name = $relation;
410 12
                $callback = function($query) use ($callback, $alias) {
411
                    /** @var $query ActiveQuery */
412 12
                    $query->alias($alias);
413 12
                    if ($callback !== null) {
414 12
                        call_user_func($callback, $query);
415 12
                    }
416 12
                };
417 12
            }
418
419 21
            if ($callback === null) {
420 21
                $relations[] = $name;
421 21
            } else {
422 18
                $relations[$name] = $callback;
423
            }
424 21
        }
425 21
        $this->joinWith[] = [$relations, $eagerLoading, $joinType];
426 21
        return $this;
427
    }
428
429 21
    private function buildJoinWith()
430
    {
431 21
        $join = $this->join;
432 21
        $this->join = [];
433
434 21
        $model = new $this->modelClass;
435 21
        foreach ($this->joinWith as $config) {
436 21
            list ($with, $eagerLoading, $joinType) = $config;
437 21
            $this->joinWithRelations($model, $with, $joinType);
438
439 21
            if (is_array($eagerLoading)) {
440
                foreach ($with as $name => $callback) {
441
                    if (is_int($name)) {
442
                        if (!in_array($callback, $eagerLoading, true)) {
443
                            unset($with[$name]);
444
                        }
445
                    } elseif (!in_array($name, $eagerLoading, true)) {
446
                        unset($with[$name]);
447
                    }
448
                }
449 21
            } elseif (!$eagerLoading) {
450 15
                $with = [];
451 15
            }
452
453 21
            $this->with($with);
454 21
        }
455
456
        // remove duplicated joins added by joinWithRelations that may be added
457
        // e.g. when joining a relation and a via relation at the same time
458 21
        $uniqueJoins = [];
459 21
        foreach ($this->join as $j) {
460 21
            $uniqueJoins[serialize($j)] = $j;
461 21
        }
462 21
        $this->join = array_values($uniqueJoins);
463
464 21
        if (!empty($join)) {
465
            // append explicit join to joinWith()
466
            // https://github.com/yiisoft/yii2/issues/2880
467
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
468
        }
469 21
    }
470
471
    /**
472
     * Inner joins with the specified relations.
473
     * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
474
     * Please refer to [[joinWith()]] for detailed usage of this method.
475
     * @param string|array $with the relations to be joined with.
476
     * @param boolean|array $eagerLoading whether to eager loading the relations.
477
     * @return $this the query object itself
478
     * @see joinWith()
479
     */
480 12
    public function innerJoinWith($with, $eagerLoading = true)
481
    {
482 12
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
483
    }
484
485
    /**
486
     * Modifies the current query by adding join fragments based on the given relations.
487
     * @param ActiveRecord $model the primary model
488
     * @param array $with the relations to be joined
489
     * @param string|array $joinType the join type
490
     */
491 21
    private function joinWithRelations($model, $with, $joinType)
492
    {
493 21
        $relations = [];
494
495 21
        foreach ($with as $name => $callback) {
496 21
            if (is_int($name)) {
497 21
                $name = $callback;
498 21
                $callback = null;
499 21
            }
500
501 21
            $primaryModel = $model;
502 21
            $parent = $this;
503 21
            $prefix = '';
504 21
            while (($pos = strpos($name, '.')) !== false) {
505 9
                $childName = substr($name, $pos + 1);
506 9
                $name = substr($name, 0, $pos);
507 9
                $fullName = $prefix === '' ? $name : "$prefix.$name";
508 9
                if (!isset($relations[$fullName])) {
509
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
510
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
511
                } else {
512 9
                    $relation = $relations[$fullName];
513
                }
514 9
                $primaryModel = new $relation->modelClass;
515 9
                $parent = $relation;
516 9
                $prefix = $fullName;
517 9
                $name = $childName;
518 9
            }
519
520 21
            $fullName = $prefix === '' ? $name : "$prefix.$name";
521 21
            if (!isset($relations[$fullName])) {
522 21
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
523 21
                if ($callback !== null) {
524 18
                    call_user_func($callback, $relation);
525 18
                }
526 21
                if (!empty($relation->joinWith)) {
527 9
                    $relation->buildJoinWith();
528 9
                }
529 21
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
530 21
            }
531 21
        }
532 21
    }
533
534
    /**
535
     * Returns the join type based on the given join type parameter and the relation name.
536
     * @param string|array $joinType the given join type(s)
537
     * @param string $name relation name
538
     * @return string the real join type
539
     */
540 21
    private function getJoinType($joinType, $name)
541
    {
542 21
        if (is_array($joinType) && isset($joinType[$name])) {
543
            return $joinType[$name];
544
        } else {
545 21
            return is_string($joinType) ? $joinType : 'INNER JOIN';
546
        }
547
    }
548
549
    /**
550
     * Returns the table name and the table alias for [[modelClass]].
551
     * @param ActiveQuery $query
552
     * @return array the table name and the table alias.
553
     */
554 24
    private function getQueryTableName($query)
555
    {
556 24
        if (empty($query->from)) {
557
            /* @var $modelClass ActiveRecord */
558 24
            $modelClass = $query->modelClass;
559 24
            $tableName = $modelClass::tableName();
560 24
        } else {
561 21
            $tableName = '';
562 21
            foreach ($query->from as $alias => $tableName) {
563 21
                if (is_string($alias)) {
564 15
                    return [$tableName, $alias];
565
                } else {
566 18
                    break;
567
                }
568 18
            }
569
        }
570
571 24
        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
572 3
            $alias = $matches[2];
573 3
        } else {
574 24
            $alias = $tableName;
575
        }
576
577 24
        return [$tableName, $alias];
578
    }
579
580
    /**
581
     * Joins a parent query with a child query.
582
     * The current query object will be modified accordingly.
583
     * @param ActiveQuery $parent
584
     * @param ActiveQuery $child
585
     * @param string $joinType
586
     */
587 21
    private function joinWithRelation($parent, $child, $joinType)
588
    {
589 21
        $via = $child->via;
590 21
        $child->via = null;
591 21
        if ($via instanceof ActiveQuery) {
592
            // via table
593 12
            $this->joinWithRelation($parent, $via, $joinType);
594 12
            $this->joinWithRelation($via, $child, $joinType);
595 12
            return;
596 21
        } elseif (is_array($via)) {
597
            // via relation
598 15
            $this->joinWithRelation($parent, $via[1], $joinType);
599 15
            $this->joinWithRelation($via[1], $child, $joinType);
600 15
            return;
601
        }
602
603 21
        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...
604 21
        list ($childTable, $childAlias) = $this->getQueryTableName($child);
605
606 21
        if (!empty($child->link)) {
607
608 21
            if (strpos($parentAlias, '{{') === false) {
609 21
                $parentAlias = '{{' . $parentAlias . '}}';
610 21
            }
611 21
            if (strpos($childAlias, '{{') === false) {
612 21
                $childAlias = '{{' . $childAlias . '}}';
613 21
            }
614
615 21
            $on = [];
616 21
            foreach ($child->link as $childColumn => $parentColumn) {
617 21
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
618 21
            }
619 21
            $on = implode(' AND ', $on);
620 21
            if (!empty($child->on)) {
621 12
                $on = ['and', $on, $child->on];
622 12
            }
623 21
        } else {
624
            $on = $child->on;
625
        }
626 21
        $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
627
628 21
        if (!empty($child->where)) {
629 9
            $this->andWhere($child->where);
630 9
        }
631 21
        if (!empty($child->having)) {
632
            $this->andHaving($child->having);
633
        }
634 21
        if (!empty($child->orderBy)) {
635 15
            $this->addOrderBy($child->orderBy);
636 15
        }
637 21
        if (!empty($child->groupBy)) {
638
            $this->addGroupBy($child->groupBy);
639
        }
640 21
        if (!empty($child->params)) {
641
            $this->addParams($child->params);
642
        }
643 21
        if (!empty($child->join)) {
644 9
            foreach ($child->join as $join) {
645 9
                $this->join[] = $join;
646 9
                $this->populateAliases((array) $join[1]);
647 9
            }
648 9
        }
649 21
        if (!empty($child->union)) {
650
            foreach ($child->union as $union) {
651
                $this->union[] = $union;
652
            }
653
        }
654 21
    }
655
656
    /**
657
     * Sets the ON condition for a relational query.
658
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
659
     * Otherwise, the condition will be used in the WHERE part of a query.
660
     *
661
     * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
662
     *
663
     * ```php
664
     * public function getActiveUsers()
665
     * {
666
     *     return $this->hasMany(User::className(), ['id' => 'user_id'])
667
     *                 ->onCondition(['active' => true]);
668
     * }
669
     * ```
670
     *
671
     * Note that this condition is applied in case of a join as well as when fetching the related records.
672
     * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
673
     * record will cause an error in a non-join-query.
674
     *
675
     * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
676
     * @param array $params the parameters (name => value) to be bound to the query.
677
     * @return $this the query object itself
678
     */
679 15
    public function onCondition($condition, $params = [])
680
    {
681 15
        $this->on = $condition;
682 15
        $this->addParams($params);
683 15
        return $this;
684
    }
685
686
    /**
687
     * Adds an additional ON condition to the existing one.
688
     * The new condition and the existing one will be joined using the 'AND' operator.
689
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
690
     * on how to specify this parameter.
691
     * @param array $params the parameters (name => value) to be bound to the query.
692
     * @return $this the query object itself
693
     * @see onCondition()
694
     * @see orOnCondition()
695
     */
696
    public function andOnCondition($condition, $params = [])
697
    {
698
        if ($this->on === null) {
699
            $this->on = $condition;
700
        } else {
701
            $this->on = ['and', $this->on, $condition];
702
        }
703
        $this->addParams($params);
704
        return $this;
705
    }
706
707
    /**
708
     * Adds an additional ON condition to the existing one.
709
     * The new condition and the existing one will be joined using the 'OR' operator.
710
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
711
     * on how to specify this parameter.
712
     * @param array $params the parameters (name => value) to be bound to the query.
713
     * @return $this the query object itself
714
     * @see onCondition()
715
     * @see andOnCondition()
716
     */
717
    public function orOnCondition($condition, $params = [])
718
    {
719
        if ($this->on === null) {
720
            $this->on = $condition;
721
        } else {
722
            $this->on = ['or', $this->on, $condition];
723
        }
724
        $this->addParams($params);
725
        return $this;
726
    }
727
728
    /**
729
     * Specifies the junction table for a relational query.
730
     *
731
     * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
732
     *
733
     * ```php
734
     * public function getItems()
735
     * {
736
     *     return $this->hasMany(Item::className(), ['id' => 'item_id'])
737
     *                 ->viaTable('order_item', ['order_id' => 'id']);
738
     * }
739
     * ```
740
     *
741
     * @param string $tableName the name of the junction table.
742
     * @param array $link the link between the junction table and the table associated with [[primaryModel]].
743
     * The keys of the array represent the columns in the junction table, and the values represent the columns
744
     * in the [[primaryModel]] table.
745
     * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
746
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
747
     * @return $this the query object itself
748
     * @see via()
749
     */
750 21
    public function viaTable($tableName, $link, callable $callable = null)
751
    {
752 21
        $relation = new ActiveQuery(get_class($this->primaryModel), [
753 21
            'from' => [$tableName],
754 21
            'link' => $link,
755 21
            'multiple' => true,
756 21
            'asArray' => true,
757 21
        ]);
758 21
        $this->via = $relation;
759 21
        if ($callable !== null) {
760 3
            call_user_func($callable, $relation);
761 3
        }
762
763 21
        return $this;
764
    }
765
766
    /**
767
     * Define an alias for the table defined in [[modelClass]].
768
     *
769
     * This method will adjust [[from]] so that an already defined alias will be overwritten.
770
     * If none was defined, [[from]] will be populated with the given alias.
771
     *
772
     * @param string $alias the table alias.
773
     * @return $this the query object itself
774
     * @since 2.0.7
775
     */
776 15
    public function alias($alias)
777
    {
778 15
        if (empty($this->from) || count($this->from) < 2) {
779 15
            list($tableName, ) = $this->getQueryTableName($this);
780 15
            $this->from = [$alias => $tableName];
781 15
        } else {
782
            /* @var $modelClass ActiveRecord */
783 3
            $modelClass = $this->modelClass;
784 3
            $tableName = $modelClass::tableName();
785
786 3
            foreach ($this->from as $key => $table) {
787 3
                if ($table === $tableName) {
788 3
                    unset($this->from[$key]);
789 3
                    $this->from[$alias] = $tableName;
790 3
                }
791 3
            }
792
        }
793 15
        $this->populateAliases($this->from);
794 15
        return $this;
795
    }
796
}
797