Completed
Push — master ( 0070b9...c9347b )
by Carsten
12:59 queued 09:16
created

ActiveQuery::prepare()   C

Complexity

Conditions 11
Paths 96

Size

Total Lines 58
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 11.121

Importance

Changes 0
Metric Value
dl 0
loc 58
ccs 27
cts 30
cp 0.9
rs 6.4179
c 0
b 0
f 0
cc 11
eloc 33
nc 96
nop 1
crap 11.121

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
 * @property string[] $tablesUsedInFrom Table names indexed by aliases. This property is read-only.
70
 *
71
 * @author Qiang Xue <[email protected]>
72
 * @author Carsten Brandt <[email protected]>
73
 * @since 2.0
74
 */
75
class ActiveQuery extends Query implements ActiveQueryInterface
76
{
77
    use ActiveQueryTrait;
78
    use ActiveRelationTrait;
79
80
    /**
81
     * @event Event an event that is triggered when the query is initialized via [[init()]].
82
     */
83
    const EVENT_INIT = 'init';
84
85
    /**
86
     * @var string the SQL statement to be executed for retrieving AR records.
87
     * This is set by [[ActiveRecord::findBySql()]].
88
     */
89
    public $sql;
90
    /**
91
     * @var string|array the join condition to be used when this query is used in a relational context.
92
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
93
     * Otherwise, the condition will be used in the WHERE part of a query.
94
     * Please refer to [[Query::where()]] on how to specify this parameter.
95
     * @see onCondition()
96
     */
97
    public $on;
98
    /**
99
     * @var array a list of relations that this query should be joined with
100
     */
101
    public $joinWith;
102
103
104
    /**
105
     * Constructor.
106
     * @param string $modelClass the model class associated with this query
107
     * @param array $config configurations to be applied to the newly created query object
108
     */
109 416
    public function __construct($modelClass, $config = [])
110
    {
111 416
        $this->modelClass = $modelClass;
112 416
        parent::__construct($config);
113 416
    }
114
115
    /**
116
     * Initializes the object.
117
     * This method is called at the end of the constructor. The default implementation will trigger
118
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
119
     * to ensure triggering of the event.
120
     */
121 416
    public function init()
122
    {
123 416
        parent::init();
124 416
        $this->trigger(self::EVENT_INIT);
125 416
    }
126
127
    /**
128
     * Executes query and returns all results as an array.
129
     * @param Connection $db the DB connection used to create the DB command.
130
     * If null, the DB connection returned by [[modelClass]] will be used.
131
     * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
132
     */
133 180
    public function all($db = null)
134
    {
135 180
        return parent::all($db);
136
    }
137
138
    /**
139
     * @inheritdoc
140
     */
141 339
    public function prepare($builder)
142
    {
143
        // NOTE: because the same ActiveQuery may be used to build different SQL statements
144
        // (e.g. by ActiveDataProvider, one for count query, the other for row data query,
145
        // it is important to make sure the same ActiveQuery can be used to build SQL statements
146
        // multiple times.
147 339
        if (!empty($this->joinWith)) {
148 45
            $this->buildJoinWith();
149 45
            $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...
150
        }
151
152 339
        if (empty($this->from)) {
153 330
            $this->from = [$this->getPrimaryTableName()];
154
        }
155
156 339
        if (empty($this->select) && !empty($this->join)) {
157 36
            list(, $alias) = $this->getTableNameAndAlias();
158 36
            $this->select = ["$alias.*"];
159
        }
160
161 339
        if ($this->primaryModel === null) {
162
            // eager loading
163 338
            $query = Query::create($this);
164
        } else {
165
            // lazy loading of a relation
166 82
            $where = $this->where;
167
168 82
            if ($this->via instanceof self) {
169
                // via junction table
170 15
                $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
171 15
                $this->filterByModels($viaModels);
172 73
            } elseif (is_array($this->via)) {
173
                // via relation
174
                /* @var $viaQuery ActiveQuery */
175 27
                list($viaName, $viaQuery) = $this->via;
176 27
                if ($viaQuery->multiple) {
177 27
                    $viaModels = $viaQuery->all();
178 27
                    $this->primaryModel->populateRelation($viaName, $viaModels);
179
                } else {
180
                    $model = $viaQuery->one();
181
                    $this->primaryModel->populateRelation($viaName, $model);
182
                    $viaModels = $model === null ? [] : [$model];
183
                }
184 27
                $this->filterByModels($viaModels);
185
            } else {
186 73
                $this->filterByModels([$this->primaryModel]);
187
            }
188
189 82
            $query = Query::create($this);
190 82
            $this->where = $where;
191
        }
192
193 339
        if (!empty($this->on)) {
194 18
            $query->andWhere($this->on);
195
        }
196
197 339
        return $query;
198
    }
199
200
    /**
201
     * @inheritdoc
202
     */
203 283
    public function populate($rows)
204
    {
205 283
        if (empty($rows)) {
206 52
            return [];
207
        }
208
209 274
        $models = $this->createModels($rows);
210 274
        if (!empty($this->join) && $this->indexBy === null) {
211 30
            $models = $this->removeDuplicatedModels($models);
212
        }
213 274
        if (!empty($this->with)) {
214 72
            $this->findWith($this->with, $models);
215
        }
216
217 274
        if ($this->inverseOf !== null) {
218 6
            $this->addInverseRelations($models);
219
        }
220
221 274
        if (!$this->asArray) {
222 264
            foreach ($models as $model) {
223 264
                $model->afterFind();
224
            }
225
        }
226
227 274
        return $models;
228
    }
229
230
    /**
231
     * Removes duplicated models by checking their primary key values.
232
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
233
     * @param array $models the models to be checked
234
     * @throws InvalidConfigException if model primary key is empty
235
     * @return array the distinctive models
236
     */
237 30
    private function removeDuplicatedModels($models)
238
    {
239 30
        $hash = [];
240
        /* @var $class ActiveRecord */
241 30
        $class = $this->modelClass;
242 30
        $pks = $class::primaryKey();
243
244 30
        if (count($pks) > 1) {
245
            // composite primary key
246 6
            foreach ($models as $i => $model) {
247 6
                $key = [];
248 6
                foreach ($pks as $pk) {
249 6
                    if (!isset($model[$pk])) {
250
                        // do not continue if the primary key is not part of the result set
251 3
                        break 2;
252
                    }
253 6
                    $key[] = $model[$pk];
254
                }
255 3
                $key = serialize($key);
256 3
                if (isset($hash[$key])) {
257
                    unset($models[$i]);
258
                } else {
259 6
                    $hash[$key] = true;
260
                }
261
            }
262
        } elseif (empty($pks)) {
263
            throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
264
        } else {
265
            // single column primary key
266 27
            $pk = reset($pks);
267 27
            foreach ($models as $i => $model) {
268 27
                if (!isset($model[$pk])) {
269
                    // do not continue if the primary key is not part of the result set
270 3
                    break;
271
                }
272 24
                $key = $model[$pk];
273 24
                if (isset($hash[$key])) {
274 12
                    unset($models[$i]);
275 24
                } elseif ($key !== null) {
276 24
                    $hash[$key] = true;
277
                }
278
            }
279
        }
280
281 30
        return array_values($models);
282
    }
283
284
    /**
285
     * Executes query and returns a single row of result.
286
     * @param Connection|null $db the DB connection used to create the DB command.
287
     * If `null`, the DB connection returned by [[modelClass]] will be used.
288
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
289
     * the query result may be either an array or an ActiveRecord object. `null` will be returned
290
     * if the query results in nothing.
291
     */
292 230
    public function one($db = null)
293
    {
294 230
        $row = parent::one($db);
295 230
        if ($row !== false) {
296 227
            $models = $this->populate([$row]);
297 227
            return reset($models) ?: null;
298
        }
299
300 24
        return null;
301
    }
302
303
    /**
304
     * Creates a DB command that can be used to execute this query.
305
     * @param Connection|null $db the DB connection used to create the DB command.
306
     * If `null`, the DB connection returned by [[modelClass]] will be used.
307
     * @return Command the created DB command instance.
308
     */
309 339
    public function createCommand($db = null)
310
    {
311
        /* @var $modelClass ActiveRecord */
312 339
        $modelClass = $this->modelClass;
313 339
        if ($db === null) {
314 328
            $db = $modelClass::getDb();
315
        }
316
317 339
        if ($this->sql === null) {
318 336
            list($sql, $params) = $db->getQueryBuilder()->build($this);
319
        } else {
320 3
            $sql = $this->sql;
321 3
            $params = $this->params;
322
        }
323
324 339
        return $db->createCommand($sql, $params);
325
    }
326
327
    /**
328
     * @inheritdoc
329
     */
330 64
    protected function queryScalar($selectExpression, $db)
331
    {
332
        /* @var $modelClass ActiveRecord */
333 64
        $modelClass = $this->modelClass;
334 64
        if ($db === null) {
335 63
            $db = $modelClass::getDb();
336
        }
337
338 64
        if ($this->sql === null) {
339 61
            return parent::queryScalar($selectExpression, $db);
340
        }
341
342 3
        return (new Query())->select([$selectExpression])
343 3
            ->from(['c' => "({$this->sql})"])
344 3
            ->params($this->params)
345 3
            ->createCommand($db)
346 3
            ->queryScalar();
347
    }
348
349
    /**
350
     * Joins with the specified relations.
351
     *
352
     * This method allows you to reuse existing relation definitions to perform JOIN queries.
353
     * Based on the definition of the specified relation(s), the method will append one or multiple
354
     * JOIN statements to the current query.
355
     *
356
     * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
357
     * which is equivalent to calling [[with()]] using the specified relations.
358
     *
359
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
360
     *
361
     * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
362
     * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
363
     *
364
     * @param string|array $with the relations to be joined. This can either be a string, representing a relation name or
365
     * an array with the following semantics:
366
     *
367
     * - Each array element represents a single relation.
368
     * - You may specify the relation name as the array key and provide an anonymous functions that
369
     *   can be used to modify the relation queries on-the-fly as the array value.
370
     * - If a relation query does not need modification, you may use the relation name as the array value.
371
     *
372
     * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
373
     *
374
     * Sub-relations can also be specified, see [[with()]] for the syntax.
375
     *
376
     * In the following you find some examples:
377
     *
378
     * ```php
379
     * // find all orders that contain books, and eager loading "books"
380
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
381
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
382
     * Order::find()->joinWith([
383
     *     'books' => function (\yii\db\ActiveQuery $query) {
384
     *         $query->orderBy('item.name');
385
     *     }
386
     * ])->all();
387
     * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
388
     * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
389
     * ```
390
     *
391
     * The alias syntax is available since version 2.0.7.
392
     *
393
     * @param bool|array $eagerLoading whether to eager load the relations specified in `$with`.
394
     * When this is a boolean, it applies to all relations specified in `$with`. Use an array
395
     * to explicitly list which relations in `$with` need to be eagerly loaded. Defaults to `true`.
396
     * @param string|array $joinType the join type of the relations specified in `$with`.
397
     * When this is a string, it applies to all relations specified in `$with`. Use an array
398
     * in the format of `relationName => joinType` to specify different join types for different relations.
399
     * @return $this the query object itself
400
     */
401 51
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
402
    {
403 51
        $relations = [];
404 51
        foreach ((array) $with as $name => $callback) {
405 51
            if (is_int($name)) {
406 51
                $name = $callback;
407 51
                $callback = null;
408
            }
409
410 51
            if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
411
                // relation is defined with an alias, adjust callback to apply alias
412 12
                list(, $relation, $alias) = $matches;
413 12
                $name = $relation;
414 12
                $callback = function ($query) use ($callback, $alias) {
415
                    /* @var $query ActiveQuery */
416 12
                    $query->alias($alias);
417 12
                    if ($callback !== null) {
418 9
                        call_user_func($callback, $query);
419
                    }
420 12
                };
421
            }
422
423 51
            if ($callback === null) {
424 48
                $relations[] = $name;
425
            } else {
426 51
                $relations[$name] = $callback;
427
            }
428
        }
429 51
        $this->joinWith[] = [$relations, $eagerLoading, $joinType];
430 51
        return $this;
431
    }
432
433 45
    private function buildJoinWith()
434
    {
435 45
        $join = $this->join;
436 45
        $this->join = [];
437
438 45
        $model = new $this->modelClass();
439 45
        foreach ($this->joinWith as $config) {
440 45
            list($with, $eagerLoading, $joinType) = $config;
441 45
            $this->joinWithRelations($model, $with, $joinType);
442
443 45
            if (is_array($eagerLoading)) {
444
                foreach ($with as $name => $callback) {
445
                    if (is_int($name)) {
446
                        if (!in_array($callback, $eagerLoading, true)) {
447
                            unset($with[$name]);
448
                        }
449
                    } elseif (!in_array($name, $eagerLoading, true)) {
450
                        unset($with[$name]);
451
                    }
452
                }
453 45
            } elseif (!$eagerLoading) {
454 15
                $with = [];
455
            }
456
457 45
            $this->with($with);
458
        }
459
460
        // remove duplicated joins added by joinWithRelations that may be added
461
        // e.g. when joining a relation and a via relation at the same time
462 45
        $uniqueJoins = [];
463 45
        foreach ($this->join as $j) {
464 45
            $uniqueJoins[serialize($j)] = $j;
465
        }
466 45
        $this->join = array_values($uniqueJoins);
467
468 45
        if (!empty($join)) {
469
            // append explicit join to joinWith()
470
            // https://github.com/yiisoft/yii2/issues/2880
471
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
472
        }
473 45
    }
474
475
    /**
476
     * Inner joins with the specified relations.
477
     * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
478
     * Please refer to [[joinWith()]] for detailed usage of this method.
479
     * @param string|array $with the relations to be joined with.
480
     * @param bool|array $eagerLoading whether to eager loading the relations.
481
     * @return $this the query object itself
482
     * @see joinWith()
483
     */
484 18
    public function innerJoinWith($with, $eagerLoading = true)
485
    {
486 18
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
487
    }
488
489
    /**
490
     * Modifies the current query by adding join fragments based on the given relations.
491
     * @param ActiveRecord $model the primary model
492
     * @param array $with the relations to be joined
493
     * @param string|array $joinType the join type
494
     */
495 45
    private function joinWithRelations($model, $with, $joinType)
496
    {
497 45
        $relations = [];
498
499 45
        foreach ($with as $name => $callback) {
500 45
            if (is_int($name)) {
501 42
                $name = $callback;
502 42
                $callback = null;
503
            }
504
505 45
            $primaryModel = $model;
506 45
            $parent = $this;
507 45
            $prefix = '';
508 45
            while (($pos = strpos($name, '.')) !== false) {
509 6
                $childName = substr($name, $pos + 1);
510 6
                $name = substr($name, 0, $pos);
511 6
                $fullName = $prefix === '' ? $name : "$prefix.$name";
512 6
                if (!isset($relations[$fullName])) {
513
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
514
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
515
                } else {
516 6
                    $relation = $relations[$fullName];
517
                }
518 6
                $primaryModel = new $relation->modelClass();
519 6
                $parent = $relation;
520 6
                $prefix = $fullName;
521 6
                $name = $childName;
522
            }
523
524 45
            $fullName = $prefix === '' ? $name : "$prefix.$name";
525 45
            if (!isset($relations[$fullName])) {
526 45
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
527 45
                if ($callback !== null) {
528 18
                    call_user_func($callback, $relation);
529
                }
530 45
                if (!empty($relation->joinWith)) {
531 6
                    $relation->buildJoinWith();
532
                }
533 45
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
534
            }
535
        }
536 45
    }
537
538
    /**
539
     * Returns the join type based on the given join type parameter and the relation name.
540
     * @param string|array $joinType the given join type(s)
541
     * @param string $name relation name
542
     * @return string the real join type
543
     */
544 45
    private function getJoinType($joinType, $name)
545
    {
546 45
        if (is_array($joinType) && isset($joinType[$name])) {
547
            return $joinType[$name];
548
        }
549
550 45
        return is_string($joinType) ? $joinType : 'INNER JOIN';
551
    }
552
553
    /**
554
     * Returns the table name and the table alias for [[modelClass]].
555
     * @return array the table name and the table alias.
556
     * @internal
557
     */
558 60
    private function getTableNameAndAlias()
559
    {
560 60
        if (empty($this->from)) {
561 54
            $tableName = $this->getPrimaryTableName();
562
        } else {
563 51
            $tableName = '';
564 51
            foreach ($this->from as $alias => $tableName) {
565 51
                if (is_string($alias)) {
566 18
                    return [$tableName, $alias];
567
                }
568 45
                break;
569
            }
570
        }
571
572 57
        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
573 3
            $alias = $matches[2];
574
        } else {
575 57
            $alias = $tableName;
576
        }
577
578 57
        return [$tableName, $alias];
579
    }
580
581
    /**
582
     * Joins a parent query with a child query.
583
     * The current query object will be modified accordingly.
584
     * @param ActiveQuery $parent
585
     * @param ActiveQuery $child
586
     * @param string $joinType
587
     */
588 45
    private function joinWithRelation($parent, $child, $joinType)
589
    {
590 45
        $via = $child->via;
591 45
        $child->via = null;
592 45
        if ($via instanceof self) {
593
            // via table
594 9
            $this->joinWithRelation($parent, $via, $joinType);
595 9
            $this->joinWithRelation($via, $child, $joinType);
596 9
            return;
597 45
        } elseif (is_array($via)) {
598
            // via relation
599 15
            $this->joinWithRelation($parent, $via[1], $joinType);
600 15
            $this->joinWithRelation($via[1], $child, $joinType);
601 15
            return;
602
        }
603
604 45
        list($parentTable, $parentAlias) = $parent->getTableNameAndAlias();
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...
605 45
        list($childTable, $childAlias) = $child->getTableNameAndAlias();
606
607 45
        if (!empty($child->link)) {
608 45
            if (strpos($parentAlias, '{{') === false) {
609 39
                $parentAlias = '{{' . $parentAlias . '}}';
610
            }
611 45
            if (strpos($childAlias, '{{') === false) {
612 45
                $childAlias = '{{' . $childAlias . '}}';
613
            }
614
615 45
            $on = [];
616 45
            foreach ($child->link as $childColumn => $parentColumn) {
617 45
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
618
            }
619 45
            $on = implode(' AND ', $on);
620 45
            if (!empty($child->on)) {
621 45
                $on = ['and', $on, $child->on];
622
            }
623
        } else {
624
            $on = $child->on;
625
        }
626 45
        $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
627
628 45
        if (!empty($child->where)) {
629 6
            $this->andWhere($child->where);
630
        }
631 45
        if (!empty($child->having)) {
632
            $this->andHaving($child->having);
633
        }
634 45
        if (!empty($child->orderBy)) {
635 15
            $this->addOrderBy($child->orderBy);
636
        }
637 45
        if (!empty($child->groupBy)) {
638
            $this->addGroupBy($child->groupBy);
639
        }
640 45
        if (!empty($child->params)) {
641
            $this->addParams($child->params);
642
        }
643 45
        if (!empty($child->join)) {
644 6
            foreach ($child->join as $join) {
645 6
                $this->join[] = $join;
646
            }
647
        }
648 45
        if (!empty($child->union)) {
649
            foreach ($child->union as $union) {
650
                $this->union[] = $union;
651
            }
652
        }
653 45
    }
654
655
    /**
656
     * Sets the ON condition for a relational query.
657
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
658
     * Otherwise, the condition will be used in the WHERE part of a query.
659
     *
660
     * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
661
     *
662
     * ```php
663
     * public function getActiveUsers()
664
     * {
665
     *     return $this->hasMany(User::className(), ['id' => 'user_id'])
666
     *                 ->onCondition(['active' => true]);
667
     * }
668
     * ```
669
     *
670
     * Note that this condition is applied in case of a join as well as when fetching the related records.
671
     * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
672
     * record will cause an error in a non-join-query.
673
     *
674
     * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
675
     * @param array $params the parameters (name => value) to be bound to the query.
676
     * @return $this the query object itself
677
     */
678 21
    public function onCondition($condition, $params = [])
679
    {
680 21
        $this->on = $condition;
681 21
        $this->addParams($params);
682 21
        return $this;
683
    }
684
685
    /**
686
     * Adds an additional ON condition to the existing one.
687
     * The new condition and the existing one will be joined using the 'AND' operator.
688
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
689
     * on how to specify this parameter.
690
     * @param array $params the parameters (name => value) to be bound to the query.
691
     * @return $this the query object itself
692
     * @see onCondition()
693
     * @see orOnCondition()
694
     */
695 6
    public function andOnCondition($condition, $params = [])
696
    {
697 6
        if ($this->on === null) {
698 3
            $this->on = $condition;
699
        } else {
700 3
            $this->on = ['and', $this->on, $condition];
701
        }
702 6
        $this->addParams($params);
703 6
        return $this;
704
    }
705
706
    /**
707
     * Adds an additional ON condition to the existing one.
708
     * The new condition and the existing one will be joined using the 'OR' operator.
709
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
710
     * on how to specify this parameter.
711
     * @param array $params the parameters (name => value) to be bound to the query.
712
     * @return $this the query object itself
713
     * @see onCondition()
714
     * @see andOnCondition()
715
     */
716 6
    public function orOnCondition($condition, $params = [])
717
    {
718 6
        if ($this->on === null) {
719 3
            $this->on = $condition;
720
        } else {
721 3
            $this->on = ['or', $this->on, $condition];
722
        }
723 6
        $this->addParams($params);
724 6
        return $this;
725
    }
726
727
    /**
728
     * Specifies the junction table for a relational query.
729
     *
730
     * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
731
     *
732
     * ```php
733
     * public function getItems()
734
     * {
735
     *     return $this->hasMany(Item::className(), ['id' => 'item_id'])
736
     *                 ->viaTable('order_item', ['order_id' => 'id']);
737
     * }
738
     * ```
739
     *
740
     * @param string $tableName the name of the junction table.
741
     * @param array $link the link between the junction table and the table associated with [[primaryModel]].
742
     * The keys of the array represent the columns in the junction table, and the values represent the columns
743
     * in the [[primaryModel]] table.
744
     * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
745
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
746
     * @return $this the query object itself
747
     * @see via()
748
     */
749 24
    public function viaTable($tableName, $link, callable $callable = null)
750
    {
751 24
        $relation = new self(get_class($this->primaryModel), [
752 24
            'from' => [$tableName],
753 24
            'link' => $link,
754
            'multiple' => true,
755
            'asArray' => true,
756
        ]);
757 24
        $this->via = $relation;
758 24
        if ($callable !== null) {
759 6
            call_user_func($callable, $relation);
760
        }
761
762 24
        return $this;
763
    }
764
765
    /**
766
     * Define an alias for the table defined in [[modelClass]].
767
     *
768
     * This method will adjust [[from]] so that an already defined alias will be overwritten.
769
     * If none was defined, [[from]] will be populated with the given alias.
770
     *
771
     * @param string $alias the table alias.
772
     * @return $this the query object itself
773
     * @since 2.0.7
774
     */
775 21
    public function alias($alias)
776
    {
777 21
        if (empty($this->from) || count($this->from) < 2) {
778 21
            list($tableName) = $this->getTableNameAndAlias();
779 21
            $this->from = [$alias => $tableName];
780
        } else {
781 3
            $tableName = $this->getPrimaryTableName();
782
783 3
            foreach ($this->from as $key => $table) {
784 3
                if ($table === $tableName) {
785 3
                    unset($this->from[$key]);
786 3
                    $this->from[$alias] = $tableName;
787
                }
788
            }
789
        }
790 21
        return $this;
791
    }
792
793
    /**
794
     * @inheritdoc
795
     * @since 2.0.12
796
     */
797 82
    public function getTablesUsedInFrom()
798
    {
799 82
        if (empty($this->from)) {
800 64
            $this->from = [$this->getPrimaryTableName()];
801
        }
802 82
        return parent::getTablesUsedInFrom();
803
    }
804
805
    /**
806
     * @return string primary table name
807
     * @since 2.0.12
808
     */
809 351
    protected function getPrimaryTableName()
810
    {
811
        /* @var $modelClass ActiveRecord */
812 351
        $modelClass = $this->modelClass;
813 351
        return $modelClass::tableName();
814
    }
815
}
816