Passed
Pull Request — master (#19805)
by Rutger
08:15
created

ActiveQuery::joinWith()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 9
nop 3
dl 0
loc 30
ccs 19
cts 19
cp 1
crap 6
rs 9.0444
c 0
b 0
f 0
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 6
                    $this->distinct();
190
                }
191
192 12
                if (!$this->viaAppliedByJoin) {
193
                    // Setup first 'via' relation in the chain based on initial link.
194 12
                    $previousRelation = $this;
195 12
                    $previousLink = $this->link;
196 12
                    while ($viaQuery) { // Loop over each 'via' chain while we got links.
197 12
                        if ($viaQuery->via) { // Check if we've got another 'via' link.
198 6
                            $nextViaQuery = ($viaQuery->via instanceof self) ? $viaQuery->via : $viaQuery->via[1];
199 6
                            $viaQuery->via = null;
200
                        } else {
201
                            // End of 'via' chain
202 12
                            $nextViaQuery = null;
203
204
                            // Get table alias for final junction table
205 12
                            list(, $viaAlias) = $viaQuery->getTableNameAndAlias();
206 12
                            if (strpos($viaAlias, '{{') === false) {
207 12
                                $viaAlias = '{{' . $viaAlias . '}}';
208
                            }
209
                            // Apply primary model relation as additional inner join `on` conditions for the final junction table.
210 12
                            foreach ($viaQuery->link as $primaryColumn => $viaColumn) {
211 12
                                $viaQuery->andOnCondition([
212 12
                                    "$viaAlias.[[$primaryColumn]]" => $this->primaryModel->getAttribute($viaColumn)
213
                                ]);
214
                            }
215
                        }
216
217 12
                        $nextLink = $viaQuery->link; // Store the current 'via' link for the next link.
218 12
                        $viaQuery->link = array_flip($previousLink); // Use the inverted previous link as the current one.
219
220
                        // Join the 'via' link on the previous link
221 12
                        $this->joinWithRelation($previousRelation, $viaQuery, 'INNER JOIN');
222
223
                        // Setup data for next iteration
224 12
                        $previousRelation = $viaQuery;
225 12
                        $viaQuery = $nextViaQuery;
226 12
                        $previousLink = $nextLink;
227
                    }
228
229
                    // Prevent duplicate application of the join(s) e.g. for ActiveDataProvider
230 12
                    $this->viaAppliedByJoin = true;
231
                }
232 127
            } elseif ($this->via instanceof self) {
233
                // via junction table
234 18
                $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
235 18
                $this->filterByModels($viaModels);
236 115
            } elseif (is_array($this->via)) {
237
                // via relation
238
                /* @var $viaQuery ActiveQuery */
239 42
                list($viaName, $viaQuery, $viaCallableUsed) = $this->via;
240 42
                if ($viaQuery->multiple) {
241 42
                    if ($viaCallableUsed) {
242 24
                        $viaModels = $viaQuery->all();
243 21
                    } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
244 3
                        $viaModels = $this->primaryModel->$viaName;
245
                    } else {
246 21
                        $viaModels = $viaQuery->all();
247 42
                        $this->primaryModel->populateRelation($viaName, $viaModels);
248
                    }
249
                } else {
250
                    if ($viaCallableUsed) {
251
                        $model = $viaQuery->one();
252
                    } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
253
                        $model = $this->primaryModel->$viaName;
254
                    } else {
255
                        $model = $viaQuery->one();
256
                        $this->primaryModel->populateRelation($viaName, $model);
257
                    }
258
                    $viaModels = $model === null ? [] : [$model];
259
                }
260 42
                $this->filterByModels($viaModels);
261
            } else {
262 115
                $this->filterByModels([$this->primaryModel]);
263
            }
264
265 139
            $query = Query::create($this);
266 139
            $this->where = $where;
267
        }
268
269 517
        if (!empty($this->on)) {
270 24
            $query->andWhere($this->on);
271
        }
272
273 517
        return $query;
274
    }
275
276
    /**
277
     * {@inheritdoc}
278
     */
279 408
    public function populate($rows)
280
    {
281 408
        if (empty($rows)) {
282 75
            return [];
283
        }
284
285 394
        $models = $this->createModels($rows);
286 394
        if (!empty($this->join) && $this->indexBy === null) {
287 69
            $models = $this->removeDuplicatedModels($models);
288
        }
289 394
        if (!empty($this->with)) {
290 129
            $this->findWith($this->with, $models);
291
        }
292
293 394
        if ($this->inverseOf !== null) {
294 12
            $this->addInverseRelations($models);
295
        }
296
297 394
        if (!$this->asArray) {
298 381
            foreach ($models as $model) {
299 381
                $model->afterFind();
300
            }
301
        }
302
303 394
        return parent::populate($models);
304
    }
305
306
    /**
307
     * Removes duplicated models by checking their primary key values.
308
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
309
     * @param array $models the models to be checked
310
     * @throws InvalidConfigException if model primary key is empty
311
     * @return array the distinctive models
312
     */
313 69
    private function removeDuplicatedModels($models)
314
    {
315 69
        $hash = [];
316
        /* @var $class ActiveRecord */
317 69
        $class = $this->modelClass;
318 69
        $pks = $class::primaryKey();
319
320 69
        if (count($pks) > 1) {
321
            // composite primary key
322 6
            foreach ($models as $i => $model) {
323 6
                $key = [];
324 6
                foreach ($pks as $pk) {
325 6
                    if (!isset($model[$pk])) {
326
                        // do not continue if the primary key is not part of the result set
327 3
                        break 2;
328
                    }
329 6
                    $key[] = $model[$pk];
330
                }
331 3
                $key = serialize($key);
332 3
                if (isset($hash[$key])) {
333
                    unset($models[$i]);
334
                } else {
335 3
                    $hash[$key] = true;
336
                }
337
            }
338
        } elseif (empty($pks)) {
339
            throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
340
        } else {
341
            // single column primary key
342 66
            $pk = reset($pks);
343 66
            foreach ($models as $i => $model) {
344 66
                if (!isset($model[$pk])) {
345
                    // do not continue if the primary key is not part of the result set
346 3
                    break;
347
                }
348 63
                $key = $model[$pk];
349 63
                if (isset($hash[$key])) {
350 24
                    unset($models[$i]);
351 63
                } elseif ($key !== null) {
352 63
                    $hash[$key] = true;
353
                }
354
            }
355
        }
356
357 69
        return array_values($models);
358
    }
359
360
    /**
361
     * Executes query and returns a single row of result.
362
     * @param Connection|null $db the DB connection used to create the DB command.
363
     * If `null`, the DB connection returned by [[modelClass]] will be used.
364
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
365
     * the query result may be either an array or an ActiveRecord object. `null` will be returned
366
     * if the query results in nothing.
367
     */
368 307
    public function one($db = null)
369
    {
370 307
        $row = parent::one($db);
371 307
        if ($row !== false) {
372 302
            $models = $this->populate([$row]);
373 302
            return reset($models) ?: null;
374
        }
375
376 29
        return null;
377
    }
378
379
    /**
380
     * Creates a DB command that can be used to execute this query.
381
     * @param Connection|null $db the DB connection used to create the DB command.
382
     * If `null`, the DB connection returned by [[modelClass]] will be used.
383
     * @return Command the created DB command instance.
384
     */
385 473
    public function createCommand($db = null)
386
    {
387
        /* @var $modelClass ActiveRecord */
388 473
        $modelClass = $this->modelClass;
389 473
        if ($db === null) {
390 459
            $db = $modelClass::getDb();
391
        }
392
393 473
        if ($this->sql === null) {
394 470
            list($sql, $params) = $db->getQueryBuilder()->build($this);
395
        } else {
396 3
            $sql = $this->sql;
397 3
            $params = $this->params;
398
        }
399
400 473
        $command = $db->createCommand($sql, $params);
401 473
        $this->setCommandCache($command);
402
403 473
        return $command;
404
    }
405
406
    /**
407
     * {@inheritdoc}
408
     */
409 65
    protected function queryScalar($selectExpression, $db)
410
    {
411
        /* @var $modelClass ActiveRecord */
412 65
        $modelClass = $this->modelClass;
413 65
        if ($db === null) {
414 64
            $db = $modelClass::getDb();
415
        }
416
417 65
        if ($this->sql === null) {
418 62
            return parent::queryScalar($selectExpression, $db);
419
        }
420
421 3
        $command = (new Query())->select([$selectExpression])
422 3
            ->from(['c' => "({$this->sql})"])
423 3
            ->params($this->params)
424 3
            ->createCommand($db);
425 3
        $this->setCommandCache($command);
426
427 3
        return $command->queryScalar();
428
    }
429
430
    /**
431
     * Joins with the specified relations.
432
     *
433
     * This method allows you to reuse existing relation definitions to perform JOIN queries.
434
     * Based on the definition of the specified relation(s), the method will append one or multiple
435
     * JOIN statements to the current query.
436
     *
437
     * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
438
     * which is equivalent to calling [[with()]] using the specified relations.
439
     *
440
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
441
     *
442
     * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
443
     * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
444
     *
445
     * @param string|array $with the relations to be joined. This can either be a string, representing a relation name or
446
     * an array with the following semantics:
447
     *
448
     * - Each array element represents a single relation.
449
     * - You may specify the relation name as the array key and provide an anonymous functions that
450
     *   can be used to modify the relation queries on-the-fly as the array value.
451
     * - If a relation query does not need modification, you may use the relation name as the array value.
452
     *
453
     * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
454
     *
455
     * Sub-relations can also be specified, see [[with()]] for the syntax.
456
     *
457
     * In the following you find some examples:
458
     *
459
     * ```php
460
     * // find all orders that contain books, and eager loading "books"
461
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
462
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
463
     * Order::find()->joinWith([
464
     *     'books' => function (\yii\db\ActiveQuery $query) {
465
     *         $query->orderBy('item.name');
466
     *     }
467
     * ])->all();
468
     * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
469
     * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
470
     * ```
471
     *
472
     * The alias syntax is available since version 2.0.7.
473
     *
474
     * @param bool|array $eagerLoading whether to eager load the relations
475
     * specified in `$with`.  When this is a boolean, it applies to all
476
     * relations specified in `$with`. Use an array to explicitly list which
477
     * relations in `$with` need to be eagerly loaded.  Note, that this does
478
     * not mean, that the relations are populated from the query result. An
479
     * extra query will still be performed to bring in the related data.
480
     * Defaults to `true`.
481
     * @param string|array $joinType the join type of the relations specified in `$with`.
482
     * When this is a string, it applies to all relations specified in `$with`. Use an array
483
     * in the format of `relationName => joinType` to specify different join types for different relations.
484
     * @return $this the query object itself
485
     */
486 93
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
487
    {
488 93
        $relations = [];
489 93
        foreach ((array) $with as $name => $callback) {
490 93
            if (is_int($name)) {
491 90
                $name = $callback;
492 90
                $callback = null;
493
            }
494
495 93
            if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
496
                // relation is defined with an alias, adjust callback to apply alias
497 18
                list(, $relation, $alias) = $matches;
498 18
                $name = $relation;
499 18
                $callback = function ($query) use ($callback, $alias) {
500
                    /* @var $query ActiveQuery */
501 18
                    $query->alias($alias);
502 18
                    if ($callback !== null) {
503 12
                        call_user_func($callback, $query);
504
                    }
505 18
                };
506
            }
507
508 93
            if ($callback === null) {
509 87
                $relations[] = $name;
510
            } else {
511 39
                $relations[$name] = $callback;
512
            }
513
        }
514 93
        $this->joinWith[] = [$relations, $eagerLoading, $joinType];
515 93
        return $this;
516
    }
517
518 87
    private function buildJoinWith()
519
    {
520 87
        $join = $this->join;
521 87
        $this->join = [];
522
523
        /* @var $modelClass ActiveRecordInterface */
524 87
        $modelClass = $this->modelClass;
525 87
        $model = $modelClass::instance();
526 87
        foreach ($this->joinWith as $config) {
527 87
            list($with, $eagerLoading, $joinType) = $config;
528 87
            $this->joinWithRelations($model, $with, $joinType);
529
530 87
            if (is_array($eagerLoading)) {
531
                foreach ($with as $name => $callback) {
532
                    if (is_int($name)) {
533
                        if (!in_array($callback, $eagerLoading, true)) {
534
                            unset($with[$name]);
535
                        }
536
                    } elseif (!in_array($name, $eagerLoading, true)) {
537
                        unset($with[$name]);
538
                    }
539
                }
540 87
            } elseif (!$eagerLoading) {
541 18
                $with = [];
542
            }
543
544 87
            $this->with($with);
545
        }
546
547
        // remove duplicated joins added by joinWithRelations that may be added
548
        // e.g. when joining a relation and a via relation at the same time
549 87
        $uniqueJoins = [];
550 87
        foreach ($this->join as $j) {
551 87
            $uniqueJoins[serialize($j)] = $j;
552
        }
553 87
        $this->join = array_values($uniqueJoins);
554
555
        // https://github.com/yiisoft/yii2/issues/16092
556 87
        $uniqueJoinsByTableName = [];
557 87
        foreach ($this->join as $config) {
558 87
            $tableName = serialize($config[1]);
559 87
            if (!array_key_exists($tableName, $uniqueJoinsByTableName)) {
560 87
                $uniqueJoinsByTableName[$tableName] = $config;
561
            }
562
        }
563 87
        $this->join = array_values($uniqueJoinsByTableName);
564
565 87
        if (!empty($join)) {
566
            // append explicit join to joinWith()
567
            // https://github.com/yiisoft/yii2/issues/2880
568
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
569
        }
570 87
    }
571
572
    /**
573
     * Inner joins with the specified relations.
574
     * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
575
     * Please refer to [[joinWith()]] for detailed usage of this method.
576
     * @param string|array $with the relations to be joined with.
577
     * @param bool|array $eagerLoading whether to eager load the relations.
578
     * Note, that this does not mean, that the relations are populated from the
579
     * query result. An extra query will still be performed to bring in the
580
     * related data.
581
     * @return $this the query object itself
582
     * @see joinWith()
583
     */
584 48
    public function innerJoinWith($with, $eagerLoading = true)
585
    {
586 48
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
587
    }
588
589
    /**
590
     * Modifies the current query by adding join fragments based on the given relations.
591
     * @param ActiveRecord $model the primary model
592
     * @param array $with the relations to be joined
593
     * @param string|array $joinType the join type
594
     */
595 87
    private function joinWithRelations($model, $with, $joinType)
596
    {
597 87
        $relations = [];
598
599 87
        foreach ($with as $name => $callback) {
600 87
            if (is_int($name)) {
601 81
                $name = $callback;
602 81
                $callback = null;
603
            }
604
605 87
            $primaryModel = $model;
606 87
            $parent = $this;
607 87
            $prefix = '';
608 87
            while (($pos = strpos($name, '.')) !== false) {
609 15
                $childName = substr($name, $pos + 1);
610 15
                $name = substr($name, 0, $pos);
611 15
                $fullName = $prefix === '' ? $name : "$prefix.$name";
612 15
                if (!isset($relations[$fullName])) {
613 9
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
614 9
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
615
                } else {
616 6
                    $relation = $relations[$fullName];
617
                }
618
                /* @var $relationModelClass ActiveRecordInterface */
619 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...
620 15
                $primaryModel = $relationModelClass::instance();
621 15
                $parent = $relation;
622 15
                $prefix = $fullName;
623 15
                $name = $childName;
624
            }
625
626 87
            $fullName = $prefix === '' ? $name : "$prefix.$name";
627 87
            if (!isset($relations[$fullName])) {
628 87
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
629 87
                if ($callback !== null) {
630 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

630
                    call_user_func(/** @scrutinizer ignore-type */ $callback, $relation);
Loading history...
631
                }
632 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...
633 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

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