Completed
Push — master ( ab24cf...d811f1 )
by Alexander
23:39 queued 20:24
created

ActiveQuery::getPrimaryTableName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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