Completed
Push — 2.1 ( 7c8525...0afc41 )
by Alexander
21:05 queued 16:02
created

ActiveQuery::populate()   C

Complexity

Conditions 8
Paths 17

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 26
ccs 14
cts 14
cp 1
rs 5.3846
cc 8
eloc 14
nc 17
nop 1
crap 8
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 409
    public function __construct($modelClass, $config = [])
110
    {
111 409
        $this->modelClass = $modelClass;
112 409
        parent::__construct($config);
113 409
    }
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 409
    public function init()
122
    {
123 409
        parent::init();
124 409
        $this->trigger(self::EVENT_INIT);
125 409
    }
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 176
    public function all($db = null)
134
    {
135 176
        return parent::all($db);
136
    }
137
138
    /**
139
     * @inheritdoc
140
     */
141 323
    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 323
        if (!empty($this->joinWith)) {
148 39
            $this->buildJoinWith();
149 39
            $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 323
        if (empty($this->from)) {
153 323
            $this->from = [$this->getPrimaryTableName()];
154
        }
155
156 323
        if (empty($this->select) && !empty($this->join)) {
157 33
            list(, $alias) = $this->getTableNameAndAlias();
158 33
            $this->select = ["$alias.*"];
159
        }
160
161 323
        if ($this->primaryModel === null) {
162
            // eager loading
163 322
            $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 323
        if (!empty($this->on)) {
194 18
            $query->andWhere($this->on);
195
        }
196
197 323
        return $query;
198
    }
199
200
    /**
201
     * @inheritdoc
202
     */
203 273
    public function populate($rows)
204
    {
205 273
        if (empty($rows)) {
206 49
            return [];
207
        }
208
209 267
        $models = $this->createModels($rows);
210 267
        if (!empty($this->join) && $this->indexBy === null) {
211 27
            $models = $this->removeDuplicatedModels($models);
212
        }
213 267
        if (!empty($this->with)) {
214 69
            $this->findWith($this->with, $models);
215
        }
216
217 267
        if ($this->inverseOf !== null) {
218 6
            $this->addInverseRelations($models);
219
        }
220
221 267
        if (!$this->asArray) {
222 258
            foreach ($models as $model) {
223 258
                $model->afterFind();
224
            }
225
        }
226
227 267
        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 27
    private function removeDuplicatedModels($models)
238
    {
239 27
        $hash = [];
240
        /* @var $class ActiveRecord */
241 27
        $class = $this->modelClass;
242 27
        $pks = $class::primaryKey();
243
244 27
        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 24
            $pk = reset($pks);
267 24
            foreach ($models as $i => $model) {
268 24
                if (!isset($model[$pk])) {
269
                    // do not continue if the primary key is not part of the result set
270 3
                    break;
271
                }
272 21
                $key = $model[$pk];
273 21
                if (isset($hash[$key])) {
274 12
                    unset($models[$i]);
275 21
                } elseif ($key !== null) {
276 21
                    $hash[$key] = true;
277
                }
278
            }
279
        }
280
281 27
        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 224
    public function one($db = null)
293
    {
294 224
        $row = parent::one($db);
295 224
        if ($row !== false) {
296 221
            $models = $this->populate([$row]);
297 221
            return reset($models) ?: null;
298
        } else {
299 24
            return null;
300
        }
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 323
    public function createCommand($db = null)
310
    {
311
        /* @var $modelClass ActiveRecord */
312 323
        $modelClass = $this->modelClass;
313 323
        if ($db === null) {
314 312
            $db = $modelClass::getDb();
315
        }
316
317 323
        if ($this->sql === null) {
318 320
            list ($sql, $params) = $db->getQueryBuilder()->build($this);
319
        } else {
320 3
            $sql = $this->sql;
321 3
            $params = $this->params;
322
        }
323
324 323
        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 45
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
402
    {
403 45
        $relations = [];
404 45
        foreach ((array) $with as $name => $callback) {
405 45
            if (is_int($name)) {
406 45
                $name = $callback;
407 45
                $callback = null;
408
            }
409
410 45
            if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
411
                // relation is defined with an alias, adjust callback to apply alias
412 9
                list(, $relation, $alias) = $matches;
413 9
                $name = $relation;
414 9
                $callback = function ($query) use ($callback, $alias) {
415
                    /** @var $query ActiveQuery */
416 9
                    $query->alias($alias);
417 9
                    if ($callback !== null) {
418 9
                        call_user_func($callback, $query);
419
                    }
420 9
                };
421
            }
422
423 45
            if ($callback === null) {
424 45
                $relations[] = $name;
425
            } else {
426 15
                $relations[$name] = $callback;
427
            }
428
        }
429 45
        $this->joinWith[] = [$relations, $eagerLoading, $joinType];
430 45
        return $this;
431
    }
432
433 39
    private function buildJoinWith()
434
    {
435 39
        $join = $this->join;
436 39
        $this->join = [];
437
438 39
        $model = new $this->modelClass;
439 39
        foreach ($this->joinWith as $config) {
440 39
            list ($with, $eagerLoading, $joinType) = $config;
441 39
            $this->joinWithRelations($model, $with, $joinType);
442
443 39
            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 39
            } elseif (!$eagerLoading) {
454 15
                $with = [];
455
            }
456
457 39
            $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 39
        $uniqueJoins = [];
463 39
        foreach ($this->join as $j) {
464 39
            $uniqueJoins[serialize($j)] = $j;
465
        }
466 39
        $this->join = array_values($uniqueJoins);
467
468 39
        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 39
    }
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 12
    public function innerJoinWith($with, $eagerLoading = true)
485
    {
486 12
        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 39
    private function joinWithRelations($model, $with, $joinType)
496
    {
497 39
        $relations = [];
498
499 39
        foreach ($with as $name => $callback) {
500 39
            if (is_int($name)) {
501 39
                $name = $callback;
502 39
                $callback = null;
503
            }
504
505 39
            $primaryModel = $model;
506 39
            $parent = $this;
507 39
            $prefix = '';
508 39
            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 39
            $fullName = $prefix === '' ? $name : "$prefix.$name";
525 39
            if (!isset($relations[$fullName])) {
526 39
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
527 39
                if ($callback !== null) {
528 15
                    call_user_func($callback, $relation);
529
                }
530 39
                if (!empty($relation->joinWith)) {
531 6
                    $relation->buildJoinWith();
532
                }
533 39
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
534
            }
535
        }
536 39
    }
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 39
    private function getJoinType($joinType, $name)
545
    {
546 39
        if (is_array($joinType) && isset($joinType[$name])) {
547
            return $joinType[$name];
548
        } else {
549 39
            return is_string($joinType) ? $joinType : 'INNER JOIN';
550
        }
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 54
    private function getTableNameAndAlias()
559
    {
560 54
        if (empty($this->from)) {
561 48
            $tableName = $this->getPrimaryTableName();
562
        } else {
563 42
            $tableName = '';
564 42
            foreach ($this->from as $alias => $tableName) {
565 42
                if (is_string($alias)) {
566 15
                    return [$tableName, $alias];
567
                } else {
568 36
                    break;
569
                }
570
            }
571
        }
572
573 51
        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
574 3
            $alias = $matches[2];
575
        } else {
576 51
            $alias = $tableName;
577
        }
578
579 51
        return [$tableName, $alias];
580
    }
581
582
    /**
583
     * Joins a parent query with a child query.
584
     * The current query object will be modified accordingly.
585
     * @param ActiveQuery $parent
586
     * @param ActiveQuery $child
587
     * @param string $joinType
588
     */
589 39
    private function joinWithRelation($parent, $child, $joinType)
590
    {
591 39
        $via = $child->via;
592 39
        $child->via = null;
593 39
        if ($via instanceof ActiveQuery) {
594
            // via table
595 9
            $this->joinWithRelation($parent, $via, $joinType);
596 9
            $this->joinWithRelation($via, $child, $joinType);
597 9
            return;
598 39
        } elseif (is_array($via)) {
599
            // via relation
600 15
            $this->joinWithRelation($parent, $via[1], $joinType);
601 15
            $this->joinWithRelation($via[1], $child, $joinType);
602 15
            return;
603
        }
604
605 39
        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...
606 39
        list ($childTable, $childAlias) = $child->getTableNameAndAlias();
607
608 39
        if (!empty($child->link)) {
609
610 39
            if (strpos($parentAlias, '{{') === false) {
611 33
                $parentAlias = '{{' . $parentAlias . '}}';
612
            }
613 39
            if (strpos($childAlias, '{{') === false) {
614 39
                $childAlias = '{{' . $childAlias . '}}';
615
            }
616
617 39
            $on = [];
618 39
            foreach ($child->link as $childColumn => $parentColumn) {
619 39
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
620
            }
621 39
            $on = implode(' AND ', $on);
622 39
            if (!empty($child->on)) {
623 9
                $on = ['and', $on, $child->on];
624
            }
625
        } else {
626
            $on = $child->on;
627
        }
628 39
        $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
629
630 39
        if (!empty($child->where)) {
631 6
            $this->andWhere($child->where);
632
        }
633 39
        if (!empty($child->having)) {
634
            $this->andHaving($child->having);
635
        }
636 39
        if (!empty($child->orderBy)) {
637 15
            $this->addOrderBy($child->orderBy);
638
        }
639 39
        if (!empty($child->groupBy)) {
640
            $this->addGroupBy($child->groupBy);
641
        }
642 39
        if (!empty($child->params)) {
643
            $this->addParams($child->params);
644
        }
645 39
        if (!empty($child->join)) {
646 6
            foreach ($child->join as $join) {
647 6
                $this->join[] = $join;
648
            }
649
        }
650 39
        if (!empty($child->union)) {
651
            foreach ($child->union as $union) {
652
                $this->union[] = $union;
653
            }
654
        }
655 39
    }
656
657
    /**
658
     * Sets the ON condition for a relational query.
659
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
660
     * Otherwise, the condition will be used in the WHERE part of a query.
661
     *
662
     * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
663
     *
664
     * ```php
665
     * public function getActiveUsers()
666
     * {
667
     *     return $this->hasMany(User::class, ['id' => 'user_id'])
668
     *                 ->onCondition(['active' => true]);
669
     * }
670
     * ```
671
     *
672
     * Note that this condition is applied in case of a join as well as when fetching the related records.
673
     * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
674
     * record will cause an error in a non-join-query.
675
     *
676
     * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
677
     * @param array $params the parameters (name => value) to be bound to the query.
678
     * @return $this the query object itself
679
     */
680 21
    public function onCondition($condition, $params = [])
681
    {
682 21
        $this->on = $condition;
683 21
        $this->addParams($params);
684 21
        return $this;
685
    }
686
687
    /**
688
     * Adds an additional ON condition to the existing one.
689
     * The new condition and the existing one will be joined using the 'AND' operator.
690
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
691
     * on how to specify this parameter.
692
     * @param array $params the parameters (name => value) to be bound to the query.
693
     * @return $this the query object itself
694
     * @see onCondition()
695
     * @see orOnCondition()
696
     */
697 6
    public function andOnCondition($condition, $params = [])
698
    {
699 6
        if ($this->on === null) {
700 3
            $this->on = $condition;
701
        } else {
702 3
            $this->on = ['and', $this->on, $condition];
703
        }
704 6
        $this->addParams($params);
705 6
        return $this;
706
    }
707
708
    /**
709
     * Adds an additional ON condition to the existing one.
710
     * The new condition and the existing one will be joined using the 'OR' operator.
711
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
712
     * on how to specify this parameter.
713
     * @param array $params the parameters (name => value) to be bound to the query.
714
     * @return $this the query object itself
715
     * @see onCondition()
716
     * @see andOnCondition()
717
     */
718 6
    public function orOnCondition($condition, $params = [])
719
    {
720 6
        if ($this->on === null) {
721 3
            $this->on = $condition;
722
        } else {
723 3
            $this->on = ['or', $this->on, $condition];
724
        }
725 6
        $this->addParams($params);
726 6
        return $this;
727
    }
728
729
    /**
730
     * Specifies the junction table for a relational query.
731
     *
732
     * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
733
     *
734
     * ```php
735
     * public function getItems()
736
     * {
737
     *     return $this->hasMany(Item::class, ['id' => 'item_id'])
738
     *                 ->viaTable('order_item', ['order_id' => 'id']);
739
     * }
740
     * ```
741
     *
742
     * @param string $tableName the name of the junction table.
743
     * @param array $link the link between the junction table and the table associated with [[primaryModel]].
744
     * The keys of the array represent the columns in the junction table, and the values represent the columns
745
     * in the [[primaryModel]] table.
746
     * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
747
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
748
     * @return $this the query object itself
749
     * @see via()
750
     */
751 24
    public function viaTable($tableName, $link, callable $callable = null)
752
    {
753 24
        $relation = new ActiveQuery(get_class($this->primaryModel), [
754 24
            'from' => [$tableName],
755 24
            'link' => $link,
756
            'multiple' => true,
757
            'asArray' => true,
758
        ]);
759 24
        $this->via = $relation;
760 24
        if ($callable !== null) {
761 6
            call_user_func($callable, $relation);
762
        }
763
764 24
        return $this;
765
    }
766
767
    /**
768
     * Define an alias for the table defined in [[modelClass]].
769
     *
770
     * This method will adjust [[from]] so that an already defined alias will be overwritten.
771
     * If none was defined, [[from]] will be populated with the given alias.
772
     *
773
     * @param string $alias the table alias.
774
     * @return $this the query object itself
775
     * @since 2.0.7
776
     */
777 18
    public function alias($alias)
778
    {
779 18
        if (empty($this->from) || count($this->from) < 2) {
780 18
            list($tableName, ) = $this->getTableNameAndAlias();
781 18
            $this->from = [$alias => $tableName];
782
        } else {
783 3
            $tableName = $this->getPrimaryTableName();
784
785 3
            foreach ($this->from as $key => $table) {
786 3
                if ($table === $tableName) {
787 3
                    unset($this->from[$key]);
788 3
                    $this->from[$alias] = $tableName;
789
                }
790
            }
791
        }
792 18
        return $this;
793
    }
794
795
    /**
796
     * Returns table names used in [[from]] indexed by aliases.
797
     * Both aliases and names are enclosed into {{ and }}.
798
     * @return string[] table names indexed by aliases
799
     * @throws \yii\base\InvalidConfigException
800
     * @since 2.0.12
801
     */
802 81
    public function getTablesUsedInFrom()
803
    {
804 81
        if (empty($this->from)) {
805 57
            $tableNames = [$this->getPrimaryTableName()];
806 24
        } elseif (is_array($this->from)) {
807 6
            $tableNames = $this->from;
808 18
        } elseif (is_string($this->from)) {
809 12
            $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
810
        } else {
811 6
            throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
812
        }
813
814
        // Clean up table names and aliases
815 75
        $cleanedUpTableNames = [];
816 75
        foreach ($tableNames as $alias => $tableName) {
817 75
            if (!is_string($alias)) {
818
                $pattern = <<<PATTERN
819 69
~
820
^
821
\s*
822
(
823
    (?:['"`\[]|{{)
824
    .*?
825
    (?:['"`\]]|}})
826
    |
827
    .*?
828
)
829
(?:
830
    (?:
831
        \s+
832
        (?:as)?
833
        \s*
834
    )
835
    (
836
       (?:['"`\[]|{{)
837
        .*?
838
        (?:['"`\]]|}})
839
        |
840
        .*?
841
    )
842
)?
843
\s*
844
$
845
~iux
846
PATTERN;
847 69
                if (preg_match($pattern, $tableName, $matches)) {
848 69
                    if (isset($matches[1])) {
849 69
                        if (isset($matches[2])) {
850 6
                            list(, $tableName, $alias) = $matches;
851
                        } else {
852 69
                            $tableName = $alias = $matches[1];
853
                        }
854 69
                        if (strncmp($alias, '{{', 2) !== 0) {
855 63
                            $alias = '{{' . $alias . '}}';
856
                        }
857 69
                        if (strncmp($tableName, '{{', 2) !== 0) {
858 63
                            $tableName = '{{' . $tableName . '}}';
859
                        }
860
                    }
861
                }
862
            }
863
864 75
            $tableName = str_replace(["'", '"', '`', '[', ']'], '', $tableName);
865 75
            $alias = str_replace(["'", '"', '`', '[', ']'], '', $alias);
866
867 75
            $cleanedUpTableNames[$alias] = $tableName;
868
        }
869
870 75
        return $cleanedUpTableNames;
871
    }
872
873
    /**
874
     * @return string primary table name
875
     * @since 2.0.12
876
     */
877 338
    protected function getPrimaryTableName()
878
    {
879
        /* @var $modelClass ActiveRecord */
880 338
        $modelClass = $this->modelClass;
881 338
        return $modelClass::tableName();
882
    }
883
}
884