Completed
Push — ar-ascollection ( 578eb6...e5ec7a )
by Alexander
09:55
created

ActiveQuery::createCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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