Issues (910)

framework/db/ActiveRelationTrait.php (1 issue)

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\InvalidArgumentException;
11
use yii\base\InvalidConfigException;
12
13
/**
14
 * ActiveRelationTrait implements the common methods and properties for active record relational queries.
15
 *
16
 * @author Qiang Xue <[email protected]>
17
 * @author Carsten Brandt <[email protected]>
18
 * @since 2.0
19
 * @phpcs:disable Squiz.NamingConventions.ValidVariableName.PrivateNoUnderscore
20
 *
21
 * @method ActiveRecordInterface|array|null one($db = null) See [[ActiveQueryInterface::one()]] for more info.
22
 * @method ActiveRecordInterface[] all($db = null) See [[ActiveQueryInterface::all()]] for more info.
23
 * @property ActiveRecord $modelClass
24
 */
25
trait ActiveRelationTrait
26
{
27
    /**
28
     * @var bool whether this query represents a relation to more than one record.
29
     * This property is only used in relational context. If true, this relation will
30
     * populate all query results into AR instances using [[Query::all()|all()]].
31
     * If false, only the first row of the results will be retrieved using [[Query::one()|one()]].
32
     */
33
    public $multiple;
34
    /**
35
     * @var ActiveRecord the primary model of a relational query.
36
     * This is used only in lazy loading with dynamic query options.
37
     */
38
    public $primaryModel;
39
    /**
40
     * @var array the columns of the primary and foreign tables that establish a relation.
41
     * The array keys must be columns of the table for this relation, and the array values
42
     * must be the corresponding columns from the primary table.
43
     * Do not prefix or quote the column names as this will be done automatically by Yii.
44
     * This property is only used in relational context.
45
     */
46
    public $link;
47
    /**
48
     * @var array|object the query associated with the junction table. Please call [[via()]]
49
     * to set this property instead of directly setting it.
50
     * This property is only used in relational context.
51
     * @see via()
52
     */
53
    public $via;
54
    /**
55
     * @var string the name of the relation that is the inverse of this relation.
56
     * For example, an order has a customer, which means the inverse of the "customer" relation
57
     * is the "orders", and the inverse of the "orders" relation is the "customer".
58
     * If this property is set, the primary record(s) will be referenced through the specified relation.
59
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
60
     * and accessing the customer of an order will not trigger new DB query.
61
     * This property is only used in relational context.
62
     * @see inverseOf()
63
     */
64
    public $inverseOf;
65
66
    private $viaMap;
67
68
    /**
69
     * Clones internal objects.
70
     */
71 16
    public function __clone()
72
    {
73 16
        parent::__clone();
74
        // make a clone of "via" object so that the same query object can be reused multiple times
75 16
        if (is_object($this->via)) {
76
            $this->via = clone $this->via;
77 16
        } elseif (is_array($this->via)) {
78 6
            $this->via = [$this->via[0], clone $this->via[1], $this->via[2]];
79
        }
80
    }
81
82
    /**
83
     * Specifies the relation associated with the junction table.
84
     *
85
     * Use this method to specify a pivot record/table when declaring a relation in the [[ActiveRecord]] class:
86
     *
87
     * ```php
88
     * class Order extends ActiveRecord
89
     * {
90
     *    public function getOrderItems() {
91
     *        return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
92
     *    }
93
     *
94
     *    public function getItems() {
95
     *        return $this->hasMany(Item::class, ['id' => 'item_id'])
96
     *                    ->via('orderItems');
97
     *    }
98
     * }
99
     * ```
100
     *
101
     * @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
102
     * @param callable|null $callable a PHP callback for customizing the relation associated with the junction table.
103
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
104
     * @return $this the relation object itself.
105
     */
106 96
    public function via($relationName, ?callable $callable = null)
107
    {
108 96
        $relation = $this->primaryModel->getRelation($relationName);
109 96
        $callableUsed = $callable !== null;
110 96
        $this->via = [$relationName, $relation, $callableUsed];
111 96
        if ($callable !== null) {
112 63
            call_user_func($callable, $relation);
113
        }
114
115 96
        return $this;
116
    }
117
118
    /**
119
     * Sets the name of the relation that is the inverse of this relation.
120
     * For example, a customer has orders, which means the inverse of the "orders" relation is the "customer".
121
     * If this property is set, the primary record(s) will be referenced through the specified relation.
122
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
123
     * and accessing the customer of an order will not trigger a new DB query.
124
     *
125
     * Use this method when declaring a relation in the [[ActiveRecord]] class, e.g. in Customer model:
126
     *
127
     * ```php
128
     * public function getOrders()
129
     * {
130
     *     return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
131
     * }
132
     * ```
133
     *
134
     * This also may be used for Order model, but with caution:
135
     *
136
     * ```php
137
     * public function getCustomer()
138
     * {
139
     *     return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
140
     * }
141
     * ```
142
     *
143
     * in this case result will depend on how order(s) was loaded.
144
     * Let's suppose customer has several orders. If only one order was loaded:
145
     *
146
     * ```php
147
     * $orders = Order::find()->where(['id' => 1])->all();
148
     * $customerOrders = $orders[0]->customer->orders;
149
     * ```
150
     *
151
     * variable `$customerOrders` will contain only one order. If orders was loaded like this:
152
     *
153
     * ```php
154
     * $orders = Order::find()->with('customer')->where(['customer_id' => 1])->all();
155
     * $customerOrders = $orders[0]->customer->orders;
156
     * ```
157
     *
158
     * variable `$customerOrders` will contain all orders of the customer.
159
     *
160
     * @param string $relationName the name of the relation that is the inverse of this relation.
161
     * @return $this the relation object itself.
162
     */
163 12
    public function inverseOf($relationName)
164
    {
165 12
        $this->inverseOf = $relationName;
166 12
        return $this;
167
    }
168
169
    /**
170
     * Finds the related records for the specified primary record.
171
     * This method is invoked when a relation of an ActiveRecord is being accessed lazily.
172
     * @param string $name the relation name
173
     * @param ActiveRecordInterface|BaseActiveRecord $model the primary model
174
     * @return mixed the related record(s)
175
     * @throws InvalidArgumentException if the relation is invalid
176
     */
177 88
    public function findFor($name, $model)
178
    {
179 88
        if (method_exists($model, 'get' . $name)) {
180 88
            $method = new \ReflectionMethod($model, 'get' . $name);
181 88
            $realName = lcfirst(substr($method->getName(), 3));
182 88
            if ($realName !== $name) {
183
                throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($model) . " has a relation named \"$realName\" instead of \"$name\".");
184
            }
185
        }
186
187 88
        return $this->multiple ? $this->all() : $this->one();
188
    }
189
190
    /**
191
     * If applicable, populate the query's primary model into the related records' inverse relationship.
192
     * @param array $result the array of related records as generated by [[populate()]]
193
     * @since 2.0.9
194
     */
195 12
    private function addInverseRelations(&$result)
196
    {
197 12
        if ($this->inverseOf === null) {
198
            return;
199
        }
200
201 12
        foreach ($result as $i => $relatedModel) {
202 12
            if ($relatedModel instanceof ActiveRecordInterface) {
203 12
                if (!isset($inverseRelation)) {
204 12
                    $inverseRelation = $relatedModel->getRelation($this->inverseOf);
205
                }
206 12
                $relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel);
207
            } else {
208 9
                if (!isset($inverseRelation)) {
209
                    /* @var $modelClass ActiveRecordInterface */
210 9
                    $modelClass = $this->modelClass;
211 9
                    $inverseRelation = $modelClass::instance()->getRelation($this->inverseOf);
212
                }
213 9
                $result[$i][$this->inverseOf] = $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel;
214
            }
215
        }
216
    }
217
218
    /**
219
     * Finds the related records and populates them into the primary models.
220
     * @param string $name the relation name
221
     * @param array $primaryModels primary models
222
     * @return array the related models
223
     * @throws InvalidConfigException if [[link]] is invalid
224
     */
225 132
    public function populateRelation($name, &$primaryModels)
226
    {
227 132
        if (!is_array($this->link)) {
228
            throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
229
        }
230
231 132
        if ($this->via instanceof self) {
232
            // via junction table
233
            /* @var $viaQuery ActiveRelationTrait */
234 9
            $viaQuery = $this->via;
235 9
            $viaModels = $viaQuery->findJunctionRows($primaryModels);
236 9
            $this->filterByModels($viaModels);
237 132
        } elseif (is_array($this->via)) {
238
            // via relation
239
            /* @var $viaQuery ActiveRelationTrait|ActiveQueryTrait */
240 54
            list($viaName, $viaQuery) = $this->via;
241 54
            if ($viaQuery->asArray === null) {
242
                // inherit asArray from primary query
243 54
                $viaQuery->asArray($this->asArray);
244
            }
245 54
            $viaQuery->primaryModel = null;
246 54
            $viaModels = array_filter($viaQuery->populateRelation($viaName, $primaryModels));
0 ignored issues
show
It seems like populateRelation() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

246
            $viaModels = array_filter($viaQuery->/** @scrutinizer ignore-call */ populateRelation($viaName, $primaryModels));
Loading history...
247 54
            $this->filterByModels($viaModels);
248
        } else {
249 132
            $this->filterByModels($primaryModels);
250
        }
251
252 132
        if (!$this->multiple && count($primaryModels) === 1) {
253 39
            $model = $this->one();
254 39
            $primaryModel = reset($primaryModels);
255 39
            if ($primaryModel instanceof ActiveRecordInterface) {
256 39
                $primaryModel->populateRelation($name, $model);
257
            } else {
258 3
                $primaryModels[key($primaryModels)][$name] = $model;
259
            }
260 39
            if ($this->inverseOf !== null) {
261 6
                $this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf);
262
            }
263
264 39
            return [$model];
265
        }
266
267
        // https://github.com/yiisoft/yii2/issues/3197
268
        // delay indexing related models after buckets are built
269 105
        $indexBy = $this->indexBy;
270 105
        $this->indexBy = null;
271 105
        $models = $this->all();
272
273 105
        if (isset($viaModels, $viaQuery)) {
274 54
            $buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery);
275
        } else {
276 105
            $buckets = $this->buildBuckets($models, $this->link);
277
        }
278
279 105
        $this->indexBy = $indexBy;
280 105
        if ($this->indexBy !== null && $this->multiple) {
281 15
            $buckets = $this->indexBuckets($buckets, $this->indexBy);
282
        }
283
284 105
        $link = array_values($this->link);
285 105
        if (isset($viaQuery)) {
286 54
            $deepViaQuery = $viaQuery;
287 54
            while ($deepViaQuery->via) {
288 6
                $deepViaQuery = is_array($deepViaQuery->via) ? $deepViaQuery->via[1] : $deepViaQuery->via;
289
            };
290 54
            $link = array_values($deepViaQuery->link);
291
        }
292 105
        foreach ($primaryModels as $i => $primaryModel) {
293 105
            $keys = null;
294 105
            if ($this->multiple && count($link) === 1) {
295 84
                $primaryModelKey = reset($link);
296 84
                $keys = isset($primaryModel[$primaryModelKey]) ? $primaryModel[$primaryModelKey] : null;
297
            }
298 105
            if (is_array($keys)) {
299
                $value = [];
300
                foreach ($keys as $key) {
301
                    $key = $this->normalizeModelKey($key);
302
                    if (isset($buckets[$key])) {
303
                        if ($this->indexBy !== null) {
304
                            // if indexBy is set, array_merge will cause renumbering of numeric array
305
                            foreach ($buckets[$key] as $bucketKey => $bucketValue) {
306
                                $value[$bucketKey] = $bucketValue;
307
                            }
308
                        } else {
309
                            $value = array_merge($value, $buckets[$key]);
310
                        }
311
                    }
312
                }
313
            } else {
314 105
                $key = $this->getModelKey($primaryModel, $link);
315 105
                $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null);
316
            }
317 105
            if ($primaryModel instanceof ActiveRecordInterface) {
318 102
                $primaryModel->populateRelation($name, $value);
319
            } else {
320 15
                $primaryModels[$i][$name] = $value;
321
            }
322
        }
323 105
        if ($this->inverseOf !== null) {
324 6
            $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
325
        }
326
327 105
        return $models;
328
    }
329
330
    /**
331
     * @param ActiveRecordInterface[] $primaryModels primary models
332
     * @param ActiveRecordInterface[] $models models
333
     * @param string $primaryName the primary relation name
334
     * @param string $name the relation name
335
     */
336 9
    private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name)
337
    {
338 9
        if (empty($models) || empty($primaryModels)) {
339
            return;
340
        }
341 9
        $model = reset($models);
342
        /* @var $relation ActiveQueryInterface|ActiveQuery */
343 9
        if ($model instanceof ActiveRecordInterface) {
344 9
            $relation = $model->getRelation($name);
345
        } else {
346
            /* @var $modelClass ActiveRecordInterface */
347 6
            $modelClass = $this->modelClass;
348 6
            $relation = $modelClass::instance()->getRelation($name);
349
        }
350
351 9
        if ($relation->multiple) {
352 6
            $buckets = $this->buildBuckets($primaryModels, $relation->link, null, null, false);
353 6
            if ($model instanceof ActiveRecordInterface) {
354 6
                foreach ($models as $model) {
355 6
                    $key = $this->getModelKey($model, $relation->link);
356 6
                    $model->populateRelation($name, isset($buckets[$key]) ? $buckets[$key] : []);
357
                }
358
            } else {
359 6
                foreach ($primaryModels as $i => $primaryModel) {
360 3
                    if ($this->multiple) {
361
                        foreach ($primaryModel as $j => $m) {
362
                            $key = $this->getModelKey($m, $relation->link);
363
                            $primaryModels[$i][$j][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
364
                        }
365 3
                    } elseif (!empty($primaryModel[$primaryName])) {
366 3
                        $key = $this->getModelKey($primaryModel[$primaryName], $relation->link);
367 3
                        $primaryModels[$i][$primaryName][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
368
                    }
369
                }
370
            }
371 6
        } elseif ($this->multiple) {
372 6
            foreach ($primaryModels as $i => $primaryModel) {
373 6
                foreach ($primaryModel[$primaryName] as $j => $m) {
374 6
                    if ($m instanceof ActiveRecordInterface) {
375 6
                        $m->populateRelation($name, $primaryModel);
376
                    } else {
377 6
                        $primaryModels[$i][$primaryName][$j][$name] = $primaryModel;
378
                    }
379
                }
380
            }
381
        } else {
382
            foreach ($primaryModels as $i => $primaryModel) {
383
                if ($primaryModels[$i][$primaryName] instanceof ActiveRecordInterface) {
384
                    $primaryModels[$i][$primaryName]->populateRelation($name, $primaryModel);
385
                } elseif (!empty($primaryModels[$i][$primaryName])) {
386
                    $primaryModels[$i][$primaryName][$name] = $primaryModel;
387
                }
388
            }
389
        }
390
    }
391
392
    /**
393
     * @param array $models
394
     * @param array $link
395
     * @param array|null $viaModels
396
     * @param self|null $viaQuery
397
     * @param bool $checkMultiple
398
     * @return array
399
     */
400 108
    private function buildBuckets($models, $link, $viaModels = null, $viaQuery = null, $checkMultiple = true)
401
    {
402 108
        if ($viaModels !== null) {
403 54
            $map = [];
404 54
            $viaLink = $viaQuery->link;
405 54
            $viaLinkKeys = array_keys($viaLink);
406 54
            $linkValues = array_values($link);
407 54
            foreach ($viaModels as $viaModel) {
408 54
                $key1 = $this->getModelKey($viaModel, $viaLinkKeys);
409 54
                $key2 = $this->getModelKey($viaModel, $linkValues);
410 54
                $map[$key2][$key1] = true;
411
            }
412
413 54
            $viaQuery->viaMap = $map;
414
415 54
            $viaVia = $viaQuery->via;
416 54
            while ($viaVia) {
417 6
                $viaViaQuery = is_array($viaVia) ? $viaVia[1] : $viaVia;
418 6
                $map = $this->mapVia($map, $viaViaQuery->viaMap);
419
420 6
                $viaVia = $viaViaQuery->via;
421
            };
422
        }
423
424 108
        $buckets = [];
425 108
        $linkKeys = array_keys($link);
426
427 108
        if (isset($map)) {
428 54
            foreach ($models as $model) {
429 54
                $key = $this->getModelKey($model, $linkKeys);
430 54
                if (isset($map[$key])) {
431 54
                    foreach (array_keys($map[$key]) as $key2) {
432 54
                        $buckets[$key2][] = $model;
433
                    }
434
                }
435
            }
436
        } else {
437 108
            foreach ($models as $model) {
438 105
                $key = $this->getModelKey($model, $linkKeys);
439 105
                $buckets[$key][] = $model;
440
            }
441
        }
442
443 108
        if ($checkMultiple && !$this->multiple) {
444 45
            foreach ($buckets as $i => $bucket) {
445 45
                $buckets[$i] = reset($bucket);
446
            }
447
        }
448
449 108
        return $buckets;
450
    }
451
452
    /**
453
     * @param array $map
454
     * @param array $viaMap
455
     * @return array
456
     */
457 6
    private function mapVia($map, $viaMap)
458
    {
459 6
        $resultMap = [];
460 6
        foreach ($map as $key => $linkKeys) {
461 6
            $resultMap[$key] = [];
462 6
            foreach (array_keys($linkKeys) as $linkKey) {
463 6
                $resultMap[$key] += $viaMap[$linkKey];
464
            }
465
        }
466 6
        return $resultMap;
467
    }
468
469
    /**
470
     * Indexes buckets by column name.
471
     *
472
     * @param array $buckets
473
     * @param string|callable $indexBy the name of the column by which the query results should be indexed by.
474
     * This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data.
475
     * @return array
476
     */
477 15
    private function indexBuckets($buckets, $indexBy)
478
    {
479 15
        $result = [];
480 15
        foreach ($buckets as $key => $models) {
481 15
            $result[$key] = [];
482 15
            foreach ($models as $model) {
483 15
                $index = is_string($indexBy) ? $model[$indexBy] : call_user_func($indexBy, $model);
484 15
                $result[$key][$index] = $model;
485
            }
486
        }
487
488 15
        return $result;
489
    }
490
491
    /**
492
     * @param array $attributes the attributes to prefix
493
     * @return array
494
     */
495 229
    private function prefixKeyColumns($attributes)
496
    {
497 229
        if ($this instanceof ActiveQuery && (!empty($this->join) || !empty($this->joinWith))) {
498 30
            if (empty($this->from)) {
499
                /* @var $modelClass ActiveRecord */
500 9
                $modelClass = $this->modelClass;
501 9
                $alias = $modelClass::tableName();
502
            } else {
503 27
                foreach ($this->from as $alias => $table) {
504 27
                    if (!is_string($alias)) {
505 27
                        $alias = $table;
506
                    }
507 27
                    break;
508
                }
509
            }
510 30
            if (isset($alias)) {
511 30
                foreach ($attributes as $i => $attribute) {
512 30
                    $attributes[$i] = "$alias.$attribute";
513
                }
514
            }
515
        }
516
517 229
        return $attributes;
518
    }
519
520
    /**
521
     * @param array $models
522
     */
523 229
    private function filterByModels($models)
524
    {
525 229
        $attributes = array_keys($this->link);
526
527 229
        $attributes = $this->prefixKeyColumns($attributes);
528
529 229
        $values = [];
530 229
        if (count($attributes) === 1) {
531
            // single key
532 223
            $attribute = reset($this->link);
533 223
            foreach ($models as $model) {
534 223
                $value = isset($model[$attribute]) || (is_object($model) && property_exists($model, $attribute)) ? $model[$attribute] : null;
535 223
                if ($value !== null) {
536 217
                    if (is_array($value)) {
537
                        $values = array_merge($values, $value);
538 217
                    } elseif ($value instanceof ArrayExpression && $value->getDimension() === 1) {
539
                        $values = array_merge($values, $value->getValue());
540
                    } else {
541 217
                        $values[] = $value;
542
                    }
543
                }
544
            }
545 223
            if (empty($values)) {
546 223
                $this->emulateExecution();
547
            }
548
        } else {
549
            // composite keys
550
551
            // ensure keys of $this->link are prefixed the same way as $attributes
552 9
            $prefixedLink = array_combine($attributes, $this->link);
553 9
            foreach ($models as $model) {
554 9
                $v = [];
555 9
                foreach ($prefixedLink as $attribute => $link) {
556 9
                    $v[$attribute] = $model[$link];
557
                }
558 9
                $values[] = $v;
559 9
                if (empty($v)) {
560
                    $this->emulateExecution();
561
                }
562
            }
563
        }
564
565 229
        if (!empty($values)) {
566 223
            $scalarValues = [];
567 223
            $nonScalarValues = [];
568 223
            foreach ($values as $value) {
569 223
                if (is_scalar($value)) {
570 217
                    $scalarValues[] = $value;
571
                } else {
572 9
                    $nonScalarValues[] = $value;
573
                }
574
            }
575
576 223
            $scalarValues = array_unique($scalarValues);
577 223
            $values = array_merge($scalarValues, $nonScalarValues);
578
        }
579
580 229
        $this->andWhere(['in', $attributes, $values]);
581
    }
582
583
    /**
584
     * @param ActiveRecordInterface|array $model
585
     * @param array $attributes
586
     * @return string|false
587
     */
588 108
    private function getModelKey($model, $attributes)
589
    {
590 108
        $key = [];
591 108
        foreach ($attributes as $attribute) {
592 108
            if (isset($model[$attribute]) || (is_object($model) && property_exists($model, $attribute))) {
593 105
                $key[] = $this->normalizeModelKey($model[$attribute]);
594
            }
595
        }
596 108
        if (count($key) > 1) {
597 3
            return serialize($key);
598
        }
599 105
        return reset($key);
600
    }
601
602
    /**
603
     * @param mixed $value raw key value. Since 2.0.40 non-string values must be convertible to string (like special
604
     * objects for cross-DBMS relations, for example: `|MongoId`).
605
     * @return string normalized key value.
606
     */
607 105
    private function normalizeModelKey($value)
608
    {
609
        try {
610 105
            return (string)$value;
611
        } catch (\Exception $e) {
612
            throw new InvalidConfigException('Value must be convertable to string.');
613
        } catch (\Throwable $e) {
614
            throw new InvalidConfigException('Value must be convertable to string.');
615
        }
616
    }
617
618
    /**
619
     * @param array $primaryModels either array of AR instances or arrays
620
     * @return array
621
     */
622 21
    private function findJunctionRows($primaryModels)
623
    {
624 21
        if (empty($primaryModels)) {
625
            return [];
626
        }
627 21
        $this->filterByModels($primaryModels);
628
        /* @var $primaryModel ActiveRecord */
629 21
        $primaryModel = reset($primaryModels);
630 21
        if (!$primaryModel instanceof ActiveRecordInterface) {
631
            // when primaryModels are array of arrays (asArray case)
632
            $primaryModel = $this->modelClass;
633
        }
634
635 21
        return $this->asArray()->all($primaryModel::getDb());
636
    }
637
}
638