Completed
Push — ar-ascollection ( 578eb6 )
by Alexander
08:56
created

ActiveQuery::populate()   D

Complexity

Conditions 9
Paths 33

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 9

Importance

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