Passed
Pull Request — master (#19805)
by Rutger
09:18
created

ActiveQuery   F

Complexity

Total Complexity 143

Size/Duplication

Total Lines 897
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
eloc 357
dl 0
loc 897
ccs 336
cts 360
cp 0.9333
rs 2
c 0
b 0
f 0
wmc 143

28 Methods

Rating   Name   Duplication   Size   Complexity  
A alias() 0 17 5
A queryScalar() 0 19 3
A createCommand() 0 19 3
A viaJoinedTable() 0 5 1
A orOnCondition() 0 9 2
A viaByJoin() 0 13 5
A all() 0 3 1
A init() 0 4 1
B joinWithRelations() 0 41 10
A innerJoinWith() 0 3 1
A getTableNameAndAlias() 0 22 5
A __construct() 0 4 1
A one() 0 9 3
F joinWithRelation() 0 63 18
A onCondition() 0 5 1
F prepare() 0 136 29
A useJoinForVia() 0 3 1
C buildJoinWith() 0 51 13
A viaTable() 0 15 3
B removeDuplicatedModels() 0 45 11
A viaJoinedTables() 0 9 2
A getJoinType() 0 7 4
A viaJoined() 0 5 1
A joinWith() 0 30 6
A getTablesUsedInFrom() 0 7 2
A getPrimaryTableName() 0 5 1
B populate() 0 25 8
A andOnCondition() 0 9 2

How to fix   Complexity   

Complex Class

Complex classes like ActiveQuery often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ActiveQuery, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use yii\base\InvalidCallException;
11
use yii\base\InvalidConfigException;
12
13
/**
14
 * ActiveQuery represents a DB query associated with an Active Record class.
15
 *
16
 * An ActiveQuery can be a normal query or be used in a relational context.
17
 *
18
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
19
 * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
20
 *
21
 * Normal Query
22
 * ------------
23
 *
24
 * ActiveQuery mainly provides the following methods to retrieve the query results:
25
 *
26
 * - [[one()]]: returns a single record populated with the first row of data.
27
 * - [[all()]]: returns all records based on the query results.
28
 * - [[count()]]: returns the number of records.
29
 * - [[sum()]]: returns the sum over the specified column.
30
 * - [[average()]]: returns the average over the specified column.
31
 * - [[min()]]: returns the min over the specified column.
32
 * - [[max()]]: returns the max over the specified column.
33
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
34
 * - [[column()]]: returns the value of the first column in the query result.
35
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
36
 *
37
 * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
38
 * [[orderBy()]] to customize the query options.
39
 *
40
 * ActiveQuery also provides the following additional query options:
41
 *
42
 * - [[with()]]: list of relations that this query should be performed with.
43
 * - [[joinWith()]]: reuse a relation query definition to add a join to a query.
44
 * - [[indexBy()]]: the name of the column by which the query result should be indexed.
45
 * - [[asArray()]]: whether to return each record as an array.
46
 *
47
 * These options can be configured using methods of the same name. For example:
48
 *
49
 * ```php
50
 * $customers = Customer::find()->with('orders')->asArray()->all();
51
 * ```
52
 *
53
 * Relational query
54
 * ----------------
55
 *
56
 * In relational context ActiveQuery represents a relation between two Active Record classes.
57
 *
58
 * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and
59
 * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
60
 * a getter method which calls one of the above methods and returns the created ActiveQuery object.
61
 *
62
 * A relation is specified by [[link]] which represents the association between columns
63
 * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
64
 *
65
 * If a relation involves a junction table, it may be specified by [[via()]] or [[viaTable()]] method.
66
 * These methods may only be called in a relational context. Same is true for [[inverseOf()]], which
67
 * marks a relation as inverse of another relation and [[onCondition()]] which adds a condition that
68
 * is to be added to relational query join condition.
69
 *
70
 * @author Qiang Xue <[email protected]>
71
 * @author Carsten Brandt <[email protected]>
72
 * @since 2.0
73
 */
74
class ActiveQuery extends Query implements ActiveQueryInterface
75
{
76
    use ActiveQueryTrait;
77
    use ActiveRelationTrait;
78
79
    /**
80
     * @event Event an event that is triggered when the query is initialized via [[init()]].
81
     */
82
    const EVENT_INIT = 'init';
83
84
    /**
85
     * @var string|null the SQL statement to be executed for retrieving AR records.
86
     * This is set by [[ActiveRecord::findBySql()]].
87
     */
88
    public $sql;
89
    /**
90
     * @var string|array|null the join condition to be used when this query is used in a relational context.
91
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
92
     * Otherwise, the condition will be used in the WHERE part of a query.
93
     * Please refer to [[Query::where()]] on how to specify this parameter.
94
     * @see onCondition()
95
     */
96
    public $on;
97
    /**
98
     * @var array|null a list of relations that this query should be joined with
99
     */
100
    public $joinWith;
101
102
    protected $useJoinForVia = false;
103
104
    protected $viaAppliedByJoin = false;
105
106
    /**
107
     * Constructor.
108
     * @param string $modelClass the model class associated with this query
109
     * @param array $config configurations to be applied to the newly created query object
110
     */
111 666
    public function __construct($modelClass, $config = [])
112
    {
113 666
        $this->modelClass = $modelClass;
114 666
        parent::__construct($config);
115 666
    }
116
117
    /**
118
     * Initializes the object.
119
     * This method is called at the end of the constructor. The default implementation will trigger
120
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
121
     * to ensure triggering of the event.
122
     */
123 666
    public function init()
124
    {
125 666
        parent::init();
126 666
        $this->trigger(self::EVENT_INIT);
127 666
    }
128
129
    /**
130
     * Executes query and returns all results as an array.
131
     * @param Connection|null $db the DB connection used to create the DB command.
132
     * If null, the DB connection returned by [[modelClass]] will be used.
133
     * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
134
     */
135 251
    public function all($db = null)
136
    {
137 251
        return parent::all($db);
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 517
    public function prepare($builder)
144
    {
145
        // NOTE: because the same ActiveQuery may be used to build different SQL statements
146
        // (e.g. by ActiveDataProvider, one for count query, the other for row data query,
147
        // it is important to make sure the same ActiveQuery can be used to build SQL statements
148
        // multiple times.
149 517
        if (!empty($this->joinWith)) {
150 84
            $this->buildJoinWith();
151 84
            $this->joinWith = null;    // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
152
        }
153
154 517
        if (empty($this->from)) {
155 484
            $this->from = [$this->getPrimaryTableName()];
156
        }
157
158 517
        if (empty($this->select) && !empty($this->join)) {
159 75
            list(, $alias) = $this->getTableNameAndAlias();
160 75
            $this->select = ["$alias.*"];
161
        }
162
163 517
        if ($this->primaryModel === null) {
164
            // eager loading
165 498
            $query = Query::create($this);
166
        } else {
167
            // lazy loading of a relation
168 139
            $where = $this->where;
169
170
            if (
171 139
                $this->useJoinForVia()
172 12
                && ($this->via instanceof self
173 139
                    || is_array($this->via)
174
                )
175
            ) {
176
                /* @var $viaQuery ActiveQuery */
177 12
                $viaQuery = ($this->via instanceof self) ? $this->via : $this->via[1];
178
179 12
                list(, $tableAlias) = $this->getTableNameAndAlias();
180 12
                if (strpos($tableAlias, '{{') === false) {
181 12
                    $tableAlias = '{{' . $tableAlias . '}}';
182
                }
183
184 12
                if (empty($this->select)) {
185 6
                    $this->select = ["$tableAlias.*"];
186
                }
187
188 12
                if (empty($this->groupBy) && !$this->distinct) {
189 12
                    $this->groupBy(array_map(
190
                        function($column) use ($tableAlias) {
191 12
                            return "$tableAlias.[[$column]]";
192 12
                        },
193 12
                        array_keys($this->link)
194
                    ));
195
                }
196
197 12
                if (!$this->viaAppliedByJoin) {
198
                    // Setup first 'via' relation in the chain based on initial link.
199 12
                    $previousRelation = $this;
200 12
                    $previousLink = $this->link;
201 12
                    while ($viaQuery) { // Loop over each 'via' chain while we got links.
202 12
                        if ($viaQuery->via) { // Check if we've got another 'via' link.
203 6
                            $nextViaQuery = ($viaQuery->via instanceof self) ? $viaQuery->via : $viaQuery->via[1];
204 6
                            $viaQuery->via = null;
205
                        } else {
206
                            // End of 'via' chain
207 12
                            $nextViaQuery = null;
208
209
                            // Get table alias for final junction table
210 12
                            list(, $viaAlias) = $viaQuery->getTableNameAndAlias();
211 12
                            if (strpos($viaAlias, '{{') === false) {
212 12
                                $viaAlias = '{{' . $viaAlias . '}}';
213
                            }
214
                            // Apply primary model relation as additional inner join `on` conditions for the final junction table.
215 12
                            foreach ($viaQuery->link as $primaryColumn => $viaColumn) {
216 12
                                $viaQuery->andOnCondition([
217 12
                                    "$viaAlias.[[$primaryColumn]]" => $this->primaryModel->getAttribute($viaColumn)
218
                                ]);
219
                            }
220
                        }
221
222 12
                        $nextLink = $viaQuery->link; // Store the current 'via' link for the next link.
223 12
                        $viaQuery->link = array_flip($previousLink); // Use the inverted previous link as the current one.
224
225
                        // Join the 'via' link on the previous link
226 12
                        $this->joinWithRelation($previousRelation, $viaQuery, 'INNER JOIN');
227
228
                        // Setup data for next iteration
229 12
                        $previousRelation = $viaQuery;
230 12
                        $viaQuery = $nextViaQuery;
231 12
                        $previousLink = $nextLink;
232
                    }
233
234
                    // Prevent duplicate application of the join(s) e.g. for ActiveDataProvider
235 12
                    $this->viaAppliedByJoin = true;
236
                }
237 127
            } elseif ($this->via instanceof self) {
238
                // via junction table
239 18
                $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
240 18
                $this->filterByModels($viaModels);
241 115
            } elseif (is_array($this->via)) {
242
                // via relation
243
                /* @var $viaQuery ActiveQuery */
244 42
                list($viaName, $viaQuery, $viaCallableUsed) = $this->via;
245 42
                if ($viaQuery->multiple) {
246 42
                    if ($viaCallableUsed) {
247 24
                        $viaModels = $viaQuery->all();
248 21
                    } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
249 3
                        $viaModels = $this->primaryModel->$viaName;
250
                    } else {
251 21
                        $viaModels = $viaQuery->all();
252 42
                        $this->primaryModel->populateRelation($viaName, $viaModels);
253
                    }
254
                } else {
255
                    if ($viaCallableUsed) {
256
                        $model = $viaQuery->one();
257
                    } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
258
                        $model = $this->primaryModel->$viaName;
259
                    } else {
260
                        $model = $viaQuery->one();
261
                        $this->primaryModel->populateRelation($viaName, $model);
262
                    }
263
                    $viaModels = $model === null ? [] : [$model];
264
                }
265 42
                $this->filterByModels($viaModels);
266
            } else {
267 115
                $this->filterByModels([$this->primaryModel]);
268
            }
269
270 139
            $query = Query::create($this);
271 139
            $this->where = $where;
272
        }
273
274 517
        if (!empty($this->on)) {
275 24
            $query->andWhere($this->on);
276
        }
277
278 517
        return $query;
279
    }
280
281
    /**
282
     * {@inheritdoc}
283
     */
284 408
    public function populate($rows)
285
    {
286 408
        if (empty($rows)) {
287 75
            return [];
288
        }
289
290 394
        $models = $this->createModels($rows);
291 394
        if (!empty($this->join) && $this->indexBy === null) {
292 69
            $models = $this->removeDuplicatedModels($models);
293
        }
294 394
        if (!empty($this->with)) {
295 129
            $this->findWith($this->with, $models);
296
        }
297
298 394
        if ($this->inverseOf !== null) {
299 12
            $this->addInverseRelations($models);
300
        }
301
302 394
        if (!$this->asArray) {
303 381
            foreach ($models as $model) {
304 381
                $model->afterFind();
305
            }
306
        }
307
308 394
        return parent::populate($models);
309
    }
310
311
    /**
312
     * Removes duplicated models by checking their primary key values.
313
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
314
     * @param array $models the models to be checked
315
     * @throws InvalidConfigException if model primary key is empty
316
     * @return array the distinctive models
317
     */
318 69
    private function removeDuplicatedModels($models)
319
    {
320 69
        $hash = [];
321
        /* @var $class ActiveRecord */
322 69
        $class = $this->modelClass;
323 69
        $pks = $class::primaryKey();
324
325 69
        if (count($pks) > 1) {
326
            // composite primary key
327 6
            foreach ($models as $i => $model) {
328 6
                $key = [];
329 6
                foreach ($pks as $pk) {
330 6
                    if (!isset($model[$pk])) {
331
                        // do not continue if the primary key is not part of the result set
332 3
                        break 2;
333
                    }
334 6
                    $key[] = $model[$pk];
335
                }
336 3
                $key = serialize($key);
337 3
                if (isset($hash[$key])) {
338
                    unset($models[$i]);
339
                } else {
340 3
                    $hash[$key] = true;
341
                }
342
            }
343
        } elseif (empty($pks)) {
344
            throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
345
        } else {
346
            // single column primary key
347 66
            $pk = reset($pks);
348 66
            foreach ($models as $i => $model) {
349 66
                if (!isset($model[$pk])) {
350
                    // do not continue if the primary key is not part of the result set
351 3
                    break;
352
                }
353 63
                $key = $model[$pk];
354 63
                if (isset($hash[$key])) {
355 24
                    unset($models[$i]);
356 63
                } elseif ($key !== null) {
357 63
                    $hash[$key] = true;
358
                }
359
            }
360
        }
361
362 69
        return array_values($models);
363
    }
364
365
    /**
366
     * Executes query and returns a single row of result.
367
     * @param Connection|null $db the DB connection used to create the DB command.
368
     * If `null`, the DB connection returned by [[modelClass]] will be used.
369
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
370
     * the query result may be either an array or an ActiveRecord object. `null` will be returned
371
     * if the query results in nothing.
372
     */
373 307
    public function one($db = null)
374
    {
375 307
        $row = parent::one($db);
376 307
        if ($row !== false) {
377 302
            $models = $this->populate([$row]);
378 302
            return reset($models) ?: null;
379
        }
380
381 29
        return null;
382
    }
383
384
    /**
385
     * Creates a DB command that can be used to execute this query.
386
     * @param Connection|null $db the DB connection used to create the DB command.
387
     * If `null`, the DB connection returned by [[modelClass]] will be used.
388
     * @return Command the created DB command instance.
389
     */
390 473
    public function createCommand($db = null)
391
    {
392
        /* @var $modelClass ActiveRecord */
393 473
        $modelClass = $this->modelClass;
394 473
        if ($db === null) {
395 459
            $db = $modelClass::getDb();
396
        }
397
398 473
        if ($this->sql === null) {
399 470
            list($sql, $params) = $db->getQueryBuilder()->build($this);
400
        } else {
401 3
            $sql = $this->sql;
402 3
            $params = $this->params;
403
        }
404
405 473
        $command = $db->createCommand($sql, $params);
406 473
        $this->setCommandCache($command);
407
408 473
        return $command;
409
    }
410
411
    /**
412
     * {@inheritdoc}
413
     */
414 65
    protected function queryScalar($selectExpression, $db)
415
    {
416
        /* @var $modelClass ActiveRecord */
417 65
        $modelClass = $this->modelClass;
418 65
        if ($db === null) {
419 64
            $db = $modelClass::getDb();
420
        }
421
422 65
        if ($this->sql === null) {
423 62
            return parent::queryScalar($selectExpression, $db);
424
        }
425
426 3
        $command = (new Query())->select([$selectExpression])
427 3
            ->from(['c' => "({$this->sql})"])
428 3
            ->params($this->params)
429 3
            ->createCommand($db);
430 3
        $this->setCommandCache($command);
431
432 3
        return $command->queryScalar();
433
    }
434
435
    /**
436
     * Joins with the specified relations.
437
     *
438
     * This method allows you to reuse existing relation definitions to perform JOIN queries.
439
     * Based on the definition of the specified relation(s), the method will append one or multiple
440
     * JOIN statements to the current query.
441
     *
442
     * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
443
     * which is equivalent to calling [[with()]] using the specified relations.
444
     *
445
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
446
     *
447
     * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
448
     * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
449
     *
450
     * @param string|array $with the relations to be joined. This can either be a string, representing a relation name or
451
     * an array with the following semantics:
452
     *
453
     * - Each array element represents a single relation.
454
     * - You may specify the relation name as the array key and provide an anonymous functions that
455
     *   can be used to modify the relation queries on-the-fly as the array value.
456
     * - If a relation query does not need modification, you may use the relation name as the array value.
457
     *
458
     * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
459
     *
460
     * Sub-relations can also be specified, see [[with()]] for the syntax.
461
     *
462
     * In the following you find some examples:
463
     *
464
     * ```php
465
     * // find all orders that contain books, and eager loading "books"
466
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
467
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
468
     * Order::find()->joinWith([
469
     *     'books' => function (\yii\db\ActiveQuery $query) {
470
     *         $query->orderBy('item.name');
471
     *     }
472
     * ])->all();
473
     * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
474
     * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
475
     * ```
476
     *
477
     * The alias syntax is available since version 2.0.7.
478
     *
479
     * @param bool|array $eagerLoading whether to eager load the relations
480
     * specified in `$with`.  When this is a boolean, it applies to all
481
     * relations specified in `$with`. Use an array to explicitly list which
482
     * relations in `$with` need to be eagerly loaded.  Note, that this does
483
     * not mean, that the relations are populated from the query result. An
484
     * extra query will still be performed to bring in the related data.
485
     * Defaults to `true`.
486
     * @param string|array $joinType the join type of the relations specified in `$with`.
487
     * When this is a string, it applies to all relations specified in `$with`. Use an array
488
     * in the format of `relationName => joinType` to specify different join types for different relations.
489
     * @return $this the query object itself
490
     */
491 93
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
492
    {
493 93
        $relations = [];
494 93
        foreach ((array) $with as $name => $callback) {
495 93
            if (is_int($name)) {
496 90
                $name = $callback;
497 90
                $callback = null;
498
            }
499
500 93
            if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
501
                // relation is defined with an alias, adjust callback to apply alias
502 18
                list(, $relation, $alias) = $matches;
503 18
                $name = $relation;
504 18
                $callback = function ($query) use ($callback, $alias) {
505
                    /* @var $query ActiveQuery */
506 18
                    $query->alias($alias);
507 18
                    if ($callback !== null) {
508 12
                        call_user_func($callback, $query);
509
                    }
510 18
                };
511
            }
512
513 93
            if ($callback === null) {
514 87
                $relations[] = $name;
515
            } else {
516 39
                $relations[$name] = $callback;
517
            }
518
        }
519 93
        $this->joinWith[] = [$relations, $eagerLoading, $joinType];
520 93
        return $this;
521
    }
522
523 87
    private function buildJoinWith()
524
    {
525 87
        $join = $this->join;
526 87
        $this->join = [];
527
528
        /* @var $modelClass ActiveRecordInterface */
529 87
        $modelClass = $this->modelClass;
530 87
        $model = $modelClass::instance();
531 87
        foreach ($this->joinWith as $config) {
532 87
            list($with, $eagerLoading, $joinType) = $config;
533 87
            $this->joinWithRelations($model, $with, $joinType);
534
535 87
            if (is_array($eagerLoading)) {
536
                foreach ($with as $name => $callback) {
537
                    if (is_int($name)) {
538
                        if (!in_array($callback, $eagerLoading, true)) {
539
                            unset($with[$name]);
540
                        }
541
                    } elseif (!in_array($name, $eagerLoading, true)) {
542
                        unset($with[$name]);
543
                    }
544
                }
545 87
            } elseif (!$eagerLoading) {
546 18
                $with = [];
547
            }
548
549 87
            $this->with($with);
550
        }
551
552
        // remove duplicated joins added by joinWithRelations that may be added
553
        // e.g. when joining a relation and a via relation at the same time
554 87
        $uniqueJoins = [];
555 87
        foreach ($this->join as $j) {
556 87
            $uniqueJoins[serialize($j)] = $j;
557
        }
558 87
        $this->join = array_values($uniqueJoins);
559
560
        // https://github.com/yiisoft/yii2/issues/16092
561 87
        $uniqueJoinsByTableName = [];
562 87
        foreach ($this->join as $config) {
563 87
            $tableName = serialize($config[1]);
564 87
            if (!array_key_exists($tableName, $uniqueJoinsByTableName)) {
565 87
                $uniqueJoinsByTableName[$tableName] = $config;
566
            }
567
        }
568 87
        $this->join = array_values($uniqueJoinsByTableName);
569
570 87
        if (!empty($join)) {
571
            // append explicit join to joinWith()
572
            // https://github.com/yiisoft/yii2/issues/2880
573
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
574
        }
575 87
    }
576
577
    /**
578
     * Inner joins with the specified relations.
579
     * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
580
     * Please refer to [[joinWith()]] for detailed usage of this method.
581
     * @param string|array $with the relations to be joined with.
582
     * @param bool|array $eagerLoading whether to eager load the relations.
583
     * Note, that this does not mean, that the relations are populated from the
584
     * query result. An extra query will still be performed to bring in the
585
     * related data.
586
     * @return $this the query object itself
587
     * @see joinWith()
588
     */
589 48
    public function innerJoinWith($with, $eagerLoading = true)
590
    {
591 48
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
592
    }
593
594
    /**
595
     * Modifies the current query by adding join fragments based on the given relations.
596
     * @param ActiveRecord $model the primary model
597
     * @param array $with the relations to be joined
598
     * @param string|array $joinType the join type
599
     */
600 87
    private function joinWithRelations($model, $with, $joinType)
601
    {
602 87
        $relations = [];
603
604 87
        foreach ($with as $name => $callback) {
605 87
            if (is_int($name)) {
606 81
                $name = $callback;
607 81
                $callback = null;
608
            }
609
610 87
            $primaryModel = $model;
611 87
            $parent = $this;
612 87
            $prefix = '';
613 87
            while (($pos = strpos($name, '.')) !== false) {
614 15
                $childName = substr($name, $pos + 1);
615 15
                $name = substr($name, 0, $pos);
616 15
                $fullName = $prefix === '' ? $name : "$prefix.$name";
617 15
                if (!isset($relations[$fullName])) {
618 9
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
619 9
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
620
                } else {
621 6
                    $relation = $relations[$fullName];
622
                }
623
                /* @var $relationModelClass ActiveRecordInterface */
624 15
                $relationModelClass = $relation->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
625 15
                $primaryModel = $relationModelClass::instance();
626 15
                $parent = $relation;
627 15
                $prefix = $fullName;
628 15
                $name = $childName;
629
            }
630
631 87
            $fullName = $prefix === '' ? $name : "$prefix.$name";
632 87
            if (!isset($relations[$fullName])) {
633 87
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
634 87
                if ($callback !== null) {
635 39
                    call_user_func($callback, $relation);
0 ignored issues
show
Bug introduced by
$callback of type null is incompatible with the type callable expected by parameter $callback of call_user_func(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

635
                    call_user_func(/** @scrutinizer ignore-type */ $callback, $relation);
Loading history...
636
                }
637 87
                if (!empty($relation->joinWith)) {
0 ignored issues
show
Bug introduced by
Accessing joinWith on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
638 9
                    $relation->buildJoinWith();
0 ignored issues
show
Bug introduced by
The method buildJoinWith() does not exist on yii\db\ActiveQueryInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to yii\db\ActiveQueryInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

638
                    $relation->/** @scrutinizer ignore-call */ 
639
                               buildJoinWith();
Loading history...
639
                }
640 87
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
641
            }
642
        }
643 87
    }
644
645
    /**
646
     * Returns the join type based on the given join type parameter and the relation name.
647
     * @param string|array $joinType the given join type(s)
648
     * @param string $name relation name
649
     * @return string the real join type
650
     */
651 87
    private function getJoinType($joinType, $name)
652
    {
653 87
        if (is_array($joinType) && isset($joinType[$name])) {
654
            return $joinType[$name];
655
        }
656
657 87
        return is_string($joinType) ? $joinType : 'INNER JOIN';
658
    }
659
660
    /**
661
     * Returns the table name and the table alias for [[modelClass]].
662
     * @return array the table name and the table alias.
663
     * @since 2.0.16
664
     */
665 153
    protected function getTableNameAndAlias()
666
    {
667 153
        if (empty($this->from)) {
668 144
            $tableName = $this->getPrimaryTableName();
669
        } else {
670 99
            $tableName = '';
671
            // if the first entry in "from" is an alias-tablename-pair return it directly
672 99
            foreach ($this->from as $alias => $tableName) {
673 99
                if (is_string($alias)) {
674 30
                    return [$tableName, $alias];
675
                }
676 90
                break;
677
            }
678
        }
679
680 150
        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
681 12
            $alias = $matches[2];
682
        } else {
683 150
            $alias = $tableName;
684
        }
685
686 150
        return [$tableName, $alias];
687
    }
688
689
    /**
690
     * Joins a parent query with a child query.
691
     * The current query object will be modified accordingly.
692
     * @param ActiveQuery $parent
693
     * @param ActiveQuery $child
694
     * @param string $joinType
695
     */
696 99
    private function joinWithRelation($parent, $child, $joinType)
697
    {
698 99
        $via = $child->via;
699 99
        $child->via = null;
700 99
        if ($via instanceof self) {
701
            // via table
702 9
            $this->joinWithRelation($parent, $via, $joinType);
703 9
            $this->joinWithRelation($via, $child, $joinType);
704 9
            return;
705 99
        } elseif (is_array($via)) {
706
            // via relation
707 27
            $this->joinWithRelation($parent, $via[1], $joinType);
708 27
            $this->joinWithRelation($via[1], $child, $joinType);
709 27
            return;
710
        }
711
712 99
        list($parentTable, $parentAlias) = $parent->getTableNameAndAlias();
713 99
        list($childTable, $childAlias) = $child->getTableNameAndAlias();
714
715 99
        if (!empty($child->link)) {
716 99
            if (strpos($parentAlias, '{{') === false) {
717 93
                $parentAlias = '{{' . $parentAlias . '}}';
718
            }
719 99
            if (strpos($childAlias, '{{') === false) {
720 99
                $childAlias = '{{' . $childAlias . '}}';
721
            }
722
723 99
            $on = [];
724 99
            foreach ($child->link as $childColumn => $parentColumn) {
725 99
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
726
            }
727 99
            $on = implode(' AND ', $on);
728 99
            if (!empty($child->on)) {
729 99
                $on = ['and', $on, $child->on];
730
            }
731
        } else {
732
            $on = $child->on;
733
        }
734 99
        $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
735
736 99
        if (!empty($child->where)) {
737 24
            $this->andWhere($child->where);
738
        }
739 99
        if (!empty($child->having)) {
740
            $this->andHaving($child->having);
741
        }
742 99
        if (!empty($child->orderBy)) {
743 33
            $this->addOrderBy($child->orderBy);
744
        }
745 99
        if (!empty($child->groupBy)) {
746
            $this->addGroupBy($child->groupBy);
747
        }
748 99
        if (!empty($child->params)) {
749
            $this->addParams($child->params);
750
        }
751 99
        if (!empty($child->join)) {
752 9
            foreach ($child->join as $join) {
753 9
                $this->join[] = $join;
754
            }
755
        }
756 99
        if (!empty($child->union)) {
757
            foreach ($child->union as $union) {
758
                $this->union[] = $union;
759
            }
760
        }
761 99
    }
762
763
    /**
764
     * Sets the ON condition for a relational query.
765
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
766
     * Otherwise, the condition will be used in the WHERE part of a query.
767
     *
768
     * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
769
     *
770
     * ```php
771
     * public function getActiveUsers()
772
     * {
773
     *     return $this->hasMany(User::class, ['id' => 'user_id'])
774
     *                 ->onCondition(['active' => true]);
775
     * }
776
     * ```
777
     *
778
     * Note that this condition is applied in case of a join as well as when fetching the related records.
779
     * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
780
     * record will cause an error in a non-join-query.
781
     *
782
     * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
783
     * @param array $params the parameters (name => value) to be bound to the query.
784
     * @return $this the query object itself
785
     */
786 21
    public function onCondition($condition, $params = [])
787
    {
788 21
        $this->on = $condition;
789 21
        $this->addParams($params);
790 21
        return $this;
791
    }
792
793
    /**
794
     * Adds an additional ON condition to the existing one.
795
     * The new condition and the existing one will be joined using the 'AND' operator.
796
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
797
     * on how to specify this parameter.
798
     * @param array $params the parameters (name => value) to be bound to the query.
799
     * @return $this the query object itself
800
     * @see onCondition()
801
     * @see orOnCondition()
802
     */
803 24
    public function andOnCondition($condition, $params = [])
804
    {
805 24
        if ($this->on === null) {
806 21
            $this->on = $condition;
807
        } else {
808 3
            $this->on = ['and', $this->on, $condition];
809
        }
810 24
        $this->addParams($params);
811 24
        return $this;
812
    }
813
814
    /**
815
     * Adds an additional ON condition to the existing one.
816
     * The new condition and the existing one will be joined using the 'OR' operator.
817
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
818
     * on how to specify this parameter.
819
     * @param array $params the parameters (name => value) to be bound to the query.
820
     * @return $this the query object itself
821
     * @see onCondition()
822
     * @see andOnCondition()
823
     */
824 6
    public function orOnCondition($condition, $params = [])
825
    {
826 6
        if ($this->on === null) {
827 3
            $this->on = $condition;
828
        } else {
829 3
            $this->on = ['or', $this->on, $condition];
830
        }
831 6
        $this->addParams($params);
832 6
        return $this;
833
    }
834
835 21
    public function viaByJoin($viaByJoin = true)
836
    {
837 21
        if (!$viaByJoin) {
838 9
            if ($this->viaAppliedByJoin) {
839 3
                throw new InvalidCallException('`viaByJoin` can not be disabled after it has been applied.');
840
            }
841 6
            if ($this->via instanceof self && !empty($this->via->via)) {
842 3
                throw new InvalidCallException('`viaByJoin` can not be disabled when using multiple "via tables".');
843
            }
844
        }
845
846 21
        $this->useJoinForVia = $viaByJoin;
847 21
        return $this;
848
    }
849
850 174
    public function useJoinForVia()
851
    {
852 174
        return $this->useJoinForVia;
853
    }
854
855 3
    public function viaJoined($relationName, callable $callable = null)
856
    {
857
        return $this
858 3
            ->viaByJoin()
859 3
            ->via($relationName, $callable);
860
    }
861
862
    /**
863
     * Specifies the junction table for a relational query.
864
     *
865
     * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
866
     *
867
     * ```php
868
     * public function getItems()
869
     * {
870
     *     return $this->hasMany(Item::class, ['id' => 'item_id'])
871
     *                 ->viaTable('order_item', ['order_id' => 'id']);
872
     * }
873
     * ```
874
     *
875
     * @param string $tableName the name of the junction table.
876
     * @param array $link the link between the junction table and the table associated with [[primaryModel]].
877
     * The keys of the array represent the columns in the junction table, and the values represent the columns
878
     * in the [[primaryModel]] table.
879
     * @param callable|null $callable a PHP callback for customizing the relation associated with the junction table.
880
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
881
     * @return $this the query object itself
882
     * @throws InvalidConfigException when query is not initialized properly
883
     * @see via()
884
     */
885 39
    public function viaTable($tableName, $link, callable $callable = null)
886
    {
887 39
        $modelClass = $this->primaryModel ? get_class($this->primaryModel) : $this->modelClass;
888 39
        $relation = new self($modelClass, [
889 39
            'from' => [$tableName],
890 39
            'link' => $link,
891
            'multiple' => true,
892
            'asArray' => true,
893
        ]);
894 39
        $this->via = $relation;
895 39
        if ($callable !== null) {
896 6
            call_user_func($callable, $relation);
897
        }
898
899 39
        return $this;
900
    }
901
902 6
    public function viaJoinedTable($tableName, $link, callable $callable = null)
903
    {
904
        return $this
905 6
            ->viaByJoin()
906 6
            ->viaTable($tableName, $link, $callable);
907
    }
908
909 6
    public function viaJoinedTables($links, callable $callable = null)
910
    {
911 6
        $this->viaByJoin();
912 6
        $query = $this;
913 6
        foreach ($links as $tableName => $link) {
914 6
            $query->viaTable($tableName, $link, $callable);
915 6
            $query = $query->via;
916
        }
917 6
        return $this;
918
    }
919
920
    /**
921
     * Define an alias for the table defined in [[modelClass]].
922
     *
923
     * This method will adjust [[from]] so that an already defined alias will be overwritten.
924
     * If none was defined, [[from]] will be populated with the given alias.
925
     *
926
     * @param string $alias the table alias.
927
     * @return $this the query object itself
928
     * @since 2.0.7
929
     */
930 72
    public function alias($alias)
931
    {
932 72
        if (empty($this->from) || count($this->from) < 2) {
933 72
            list($tableName) = $this->getTableNameAndAlias();
934 72
            $this->from = [$alias => $tableName];
935
        } else {
936 3
            $tableName = $this->getPrimaryTableName();
937
938 3
            foreach ($this->from as $key => $table) {
939 3
                if ($table === $tableName) {
940 3
                    unset($this->from[$key]);
941 3
                    $this->from[$alias] = $tableName;
942
                }
943
            }
944
        }
945
946 72
        return $this;
947
    }
948
949
    /**
950
     * {@inheritdoc}
951
     * @since 2.0.12
952
     */
953 257
    public function getTablesUsedInFrom()
954
    {
955 257
        if (empty($this->from)) {
956 173
            return $this->cleanUpTableNames([$this->getPrimaryTableName()]);
957
        }
958
959 84
        return parent::getTablesUsedInFrom();
960
    }
961
962
    /**
963
     * @return string primary table name
964
     * @since 2.0.12
965
     */
966 559
    protected function getPrimaryTableName()
967
    {
968
        /* @var $modelClass ActiveRecord */
969 559
        $modelClass = $this->modelClass;
970 559
        return $modelClass::tableName();
971
    }
972
}
973