Passed
Push — master ( 9dbdd9...d5a428 )
by Alexander
04:15
created

framework/db/ActiveRelationTrait.php (1 issue)

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use yii\base\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
 *
20
 * @method ActiveRecordInterface one($db = null)
21
 * @method ActiveRecordInterface[] all($db = null)
22
 * @property ActiveRecord $modelClass
23
 */
24
trait ActiveRelationTrait
25
{
26
    /**
27
     * @var bool whether this query represents a relation to more than one record.
28
     * This property is only used in relational context. If true, this relation will
29
     * populate all query results into AR instances using [[Query::all()|all()]].
30
     * If false, only the first row of the results will be retrieved using [[Query::one()|one()]].
31
     */
32
    public $multiple;
33
    /**
34
     * @var ActiveRecord the primary model of a relational query.
35
     * This is used only in lazy loading with dynamic query options.
36
     */
37
    public $primaryModel;
38
    /**
39
     * @var array the columns of the primary and foreign tables that establish a relation.
40
     * The array keys must be columns of the table for this relation, and the array values
41
     * must be the corresponding columns from the primary table.
42
     * Do not prefix or quote the column names as this will be done automatically by Yii.
43
     * This property is only used in relational context.
44
     */
45
    public $link;
46
    /**
47
     * @var array|object the query associated with the junction table. Please call [[via()]]
48
     * to set this property instead of directly setting it.
49
     * This property is only used in relational context.
50
     * @see via()
51
     */
52
    public $via;
53
    /**
54
     * @var string the name of the relation that is the inverse of this relation.
55
     * For example, an order has a customer, which means the inverse of the "customer" relation
56
     * is the "orders", and the inverse of the "orders" relation is the "customer".
57
     * If this property is set, the primary record(s) will be referenced through the specified relation.
58
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
59
     * and accessing the customer of an order will not trigger new DB query.
60
     * This property is only used in relational context.
61
     * @see inverseOf()
62
     */
63
    public $inverseOf;
64
65
    private $viaMap;
66
67
    /**
68
     * Clones internal objects.
69
     */
70 21
    public function __clone()
71
    {
72 21
        parent::__clone();
73
        // make a clone of "via" object so that the same query object can be reused multiple times
74 21
        if (is_object($this->via)) {
75
            $this->via = clone $this->via;
76 21
        } elseif (is_array($this->via)) {
77 10
            $this->via = [$this->via[0], clone $this->via[1], $this->via[2]];
78
        }
79 21
    }
80
81
    /**
82
     * Specifies the relation associated with the junction table.
83
     *
84
     * Use this method to specify a pivot record/table when declaring a relation in the [[ActiveRecord]] class:
85
     *
86
     * ```php
87
     * class Order extends ActiveRecord
88
     * {
89
     *    public function getOrderItems() {
90
     *        return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
91
     *    }
92
     *
93
     *    public function getItems() {
94
     *        return $this->hasMany(Item::class, ['id' => 'item_id'])
95
     *                    ->via('orderItems');
96
     *    }
97
     * }
98
     * ```
99
     *
100
     * @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
101
     * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
102
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
103
     * @return $this the relation object itself.
104
     */
105 150
    public function via($relationName, callable $callable = null)
106
    {
107 150
        $relation = $this->primaryModel->getRelation($relationName);
108 150
        $callableUsed = $callable !== null;
109 150
        $this->via = [$relationName, $relation, $callableUsed];
110 150
        if ($callable !== null) {
111 100
            call_user_func($callable, $relation);
112
        }
113
114 150
        return $this;
115
    }
116
117
    /**
118
     * Sets the name of the relation that is the inverse of this relation.
119
     * For example, a customer has orders, which means the inverse of the "orders" relation is the "customer".
120
     * If this property is set, the primary record(s) will be referenced through the specified relation.
121
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
122
     * and accessing the customer of an order will not trigger a new DB query.
123
     *
124
     * Use this method when declaring a relation in the [[ActiveRecord]] class, e.g. in Customer model:
125
     *
126
     * ```php
127
     * public function getOrders()
128
     * {
129
     *     return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
130
     * }
131
     * ```
132
     *
133
     * This also may be used for Order model, but with caution:
134
     *
135
     * ```php
136
     * public function getCustomer()
137
     * {
138
     *     return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
139
     * }
140
     * ```
141
     *
142
     * in this case result will depend on how order(s) was loaded.
143
     * Let's suppose customer has several orders. If only one order was loaded:
144
     *
145
     * ```php
146
     * $orders = Order::find()->where(['id' => 1])->all();
147
     * $customerOrders = $orders[0]->customer->orders;
148
     * ```
149
     *
150
     * variable `$customerOrders` will contain only one order. If orders was loaded like this:
151
     *
152
     * ```php
153
     * $orders = Order::find()->with('customer')->where(['customer_id' => 1])->all();
154
     * $customerOrders = $orders[0]->customer->orders;
155
     * ```
156
     *
157
     * variable `$customerOrders` will contain all orders of the customer.
158
     *
159
     * @param string $relationName the name of the relation that is the inverse of this relation.
160
     * @return $this the relation object itself.
161
     */
162 20
    public function inverseOf($relationName)
163
    {
164 20
        $this->inverseOf = $relationName;
165 20
        return $this;
166
    }
167
168
    /**
169
     * Finds the related records for the specified primary record.
170
     * This method is invoked when a relation of an ActiveRecord is being accessed in a lazy fashion.
171
     * @param string $name the relation name
172
     * @param ActiveRecordInterface|BaseActiveRecord $model the primary model
173
     * @return mixed the related record(s)
174
     * @throws InvalidArgumentException if the relation is invalid
175
     */
176 136
    public function findFor($name, $model)
177
    {
178 136
        if (method_exists($model, 'get' . $name)) {
179 136
            $method = new \ReflectionMethod($model, 'get' . $name);
180 136
            $realName = lcfirst(substr($method->getName(), 3));
181 136
            if ($realName !== $name) {
182
                throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($model) . " has a relation named \"$realName\" instead of \"$name\".");
183
            }
184
        }
185
186 136
        return $this->multiple ? $this->all() : $this->one();
187
    }
188
189
    /**
190
     * If applicable, populate the query's primary model into the related records' inverse relationship.
191
     * @param array $result the array of related records as generated by [[populate()]]
192
     * @since 2.0.9
193
     */
194 20
    private function addInverseRelations(&$result)
195
    {
196 20
        if ($this->inverseOf === null) {
197
            return;
198
        }
199
200 20
        foreach ($result as $i => $relatedModel) {
201 20
            if ($relatedModel instanceof ActiveRecordInterface) {
202 20
                if (!isset($inverseRelation)) {
203 20
                    $inverseRelation = $relatedModel->getRelation($this->inverseOf);
204
                }
205 20
                $relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel);
206
            } else {
207 15
                if (!isset($inverseRelation)) {
208
                    /* @var $modelClass ActiveRecordInterface */
209 15
                    $modelClass = $this->modelClass;
210 15
                    $inverseRelation = $modelClass::instance()->getRelation($this->inverseOf);
211
                }
212 20
                $result[$i][$this->inverseOf] = $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel;
213
            }
214
        }
215 20
    }
216
217
    /**
218
     * Finds the related records and populates them into the primary models.
219
     * @param string $name the relation name
220
     * @param array $primaryModels primary models
221
     * @return array the related models
222
     * @throws InvalidConfigException if [[link]] is invalid
223
     */
224 203
    public function populateRelation($name, &$primaryModels)
225
    {
226 203
        if (!is_array($this->link)) {
227
            throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
228
        }
229
230 203
        if ($this->via instanceof self) {
231
            // via junction table
232
            /* @var $viaQuery ActiveRelationTrait */
233 15
            $viaQuery = $this->via;
234 15
            $viaModels = $viaQuery->findJunctionRows($primaryModels);
235 15
            $this->filterByModels($viaModels);
236 203
        } elseif (is_array($this->via)) {
237
            // via relation
238
            /* @var $viaQuery ActiveRelationTrait|ActiveQueryTrait */
239 80
            list($viaName, $viaQuery) = $this->via;
240 80
            if ($viaQuery->asArray === null) {
241
                // inherit asArray from primary query
242 80
                $viaQuery->asArray($this->asArray);
243
            }
244 80
            $viaQuery->primaryModel = null;
245 80
            $viaModels = array_filter($viaQuery->populateRelation($viaName, $primaryModels));
246 80
            $this->filterByModels($viaModels);
247
        } else {
248 203
            $this->filterByModels($primaryModels);
249
        }
250
251 203
        if (!$this->multiple && count($primaryModels) === 1) {
252 65
            $model = $this->one();
253 65
            $primaryModel = reset($primaryModels);
254 65
            if ($primaryModel instanceof ActiveRecordInterface) {
255 65
                $primaryModel->populateRelation($name, $model);
256
            } else {
257 5
                $primaryModels[key($primaryModels)][$name] = $model;
258
            }
259 65
            if ($this->inverseOf !== null) {
260 10
                $this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf);
261
            }
262
263 65
            return [$model];
264
        }
265
266
        // https://github.com/yiisoft/yii2/issues/3197
267
        // delay indexing related models after buckets are built
268 158
        $indexBy = $this->indexBy;
269 158
        $this->indexBy = null;
0 ignored issues
show
Bug Best Practice introduced by
The property indexBy does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
270 158
        $models = $this->all();
271
272 158
        if (isset($viaModels, $viaQuery)) {
273 80
            $buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery);
274
        } else {
275 158
            $buckets = $this->buildBuckets($models, $this->link);
276
        }
277
278 158
        $this->indexBy = $indexBy;
279 158
        if ($this->indexBy !== null && $this->multiple) {
280 25
            $buckets = $this->indexBuckets($buckets, $this->indexBy);
281
        }
282
283 158
        $link = array_values($this->link);
284 158
        if (isset($viaQuery)) {
285 80
            $deepViaQuery = $viaQuery;
286 80
            while ($deepViaQuery->via) {
287 5
                $deepViaQuery = is_array($deepViaQuery->via) ? $deepViaQuery->via[1] : $deepViaQuery->via;
288
            };
289 80
            $link = array_values($deepViaQuery->link);
290
        }
291 158
        foreach ($primaryModels as $i => $primaryModel) {
292 158
            if ($this->multiple && count($link) === 1 && is_array($keys = $primaryModel[reset($link)])) {
293
                $value = [];
294
                foreach ($keys as $key) {
295
                    $key = $this->normalizeModelKey($key);
296
                    if (isset($buckets[$key])) {
297
                        if ($this->indexBy !== null) {
298
                            // if indexBy is set, array_merge will cause renumbering of numeric array
299
                            foreach ($buckets[$key] as $bucketKey => $bucketValue) {
300
                                $value[$bucketKey] = $bucketValue;
301
                            }
302
                        } else {
303
                            $value = array_merge($value, $buckets[$key]);
304
                        }
305
                    }
306
                }
307
            } else {
308 158
                $key = $this->getModelKey($primaryModel, $link);
309 158
                $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null);
310
            }
311 158
            if ($primaryModel instanceof ActiveRecordInterface) {
312 158
                $primaryModel->populateRelation($name, $value);
313
            } else {
314 158
                $primaryModels[$i][$name] = $value;
315
            }
316
        }
317 158
        if ($this->inverseOf !== null) {
318 10
            $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
319
        }
320
321 158
        return $models;
322
    }
323
324
    /**
325
     * @param ActiveRecordInterface[] $primaryModels primary models
326
     * @param ActiveRecordInterface[] $models models
327
     * @param string $primaryName the primary relation name
328
     * @param string $name the relation name
329
     */
330 15
    private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name)
331
    {
332 15
        if (empty($models) || empty($primaryModels)) {
333
            return;
334
        }
335 15
        $model = reset($models);
336
        /* @var $relation ActiveQueryInterface|ActiveQuery */
337 15
        if ($model instanceof ActiveRecordInterface) {
338 15
            $relation = $model->getRelation($name);
339
        } else {
340
            /* @var $modelClass ActiveRecordInterface */
341 10
            $modelClass = $this->modelClass;
342 10
            $relation = $modelClass::instance()->getRelation($name);
343
        }
344
345 15
        if ($relation->multiple) {
346 10
            $buckets = $this->buildBuckets($primaryModels, $relation->link, null, null, false);
347 10
            if ($model instanceof ActiveRecordInterface) {
348 10
                foreach ($models as $model) {
349 10
                    $key = $this->getModelKey($model, $relation->link);
350 10
                    $model->populateRelation($name, isset($buckets[$key]) ? $buckets[$key] : []);
351
                }
352
            } else {
353 5
                foreach ($primaryModels as $i => $primaryModel) {
354 5
                    if ($this->multiple) {
355
                        foreach ($primaryModel as $j => $m) {
356
                            $key = $this->getModelKey($m, $relation->link);
357
                            $primaryModels[$i][$j][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
358
                        }
359 5
                    } elseif (!empty($primaryModel[$primaryName])) {
360 5
                        $key = $this->getModelKey($primaryModel[$primaryName], $relation->link);
361 10
                        $primaryModels[$i][$primaryName][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
362
                    }
363
                }
364
            }
365 10
        } elseif ($this->multiple) {
366 10
            foreach ($primaryModels as $i => $primaryModel) {
367 10
                foreach ($primaryModel[$primaryName] as $j => $m) {
368 10
                    if ($m instanceof ActiveRecordInterface) {
369 10
                        $m->populateRelation($name, $primaryModel);
370
                    } else {
371 10
                        $primaryModels[$i][$primaryName][$j][$name] = $primaryModel;
372
                    }
373
                }
374
            }
375
        } else {
376
            foreach ($primaryModels as $i => $primaryModel) {
377
                if ($primaryModels[$i][$primaryName] instanceof ActiveRecordInterface) {
378
                    $primaryModels[$i][$primaryName]->populateRelation($name, $primaryModel);
379
                } elseif (!empty($primaryModels[$i][$primaryName])) {
380
                    $primaryModels[$i][$primaryName][$name] = $primaryModel;
381
                }
382
            }
383
        }
384 15
    }
385
386
    /**
387
     * @param array $models
388
     * @param array $link
389
     * @param array $viaModels
390
     * @param null|self $viaQuery
391
     * @param bool $checkMultiple
392
     * @return array
393
     */
394 163
    private function buildBuckets($models, $link, $viaModels = null, $viaQuery = null, $checkMultiple = true)
395
    {
396 163
        if ($viaModels !== null) {
397 80
            $map = [];
398 80
            $viaLink = $viaQuery->link;
399 80
            $viaLinkKeys = array_keys($viaLink);
400 80
            $linkValues = array_values($link);
401 80
            foreach ($viaModels as $viaModel) {
402 80
                $key1 = $this->getModelKey($viaModel, $viaLinkKeys);
403 80
                $key2 = $this->getModelKey($viaModel, $linkValues);
404 80
                $map[$key2][$key1] = true;
405
            }
406
407 80
            $viaQuery->viaMap = $map;
408
409 80
            $viaVia = $viaQuery->via;
410 80
            while ($viaVia) {
411 5
                $viaViaQuery = is_array($viaVia) ? $viaVia[1] : $viaVia;
412 5
                $map = $this->mapVia($map, $viaViaQuery->viaMap);
413
414 5
                $viaVia = $viaViaQuery->via;
415
            };
416
        }
417
418 163
        $buckets = [];
419 163
        $linkKeys = array_keys($link);
420
421 163
        if (isset($map)) {
422 80
            foreach ($models as $model) {
423 80
                $key = $this->getModelKey($model, $linkKeys);
424 80
                if (isset($map[$key])) {
425 80
                    foreach (array_keys($map[$key]) as $key2) {
426 80
                        $buckets[$key2][] = $model;
427
                    }
428
                }
429
            }
430
        } else {
431 163
            foreach ($models as $model) {
432 163
                $key = $this->getModelKey($model, $linkKeys);
433 163
                $buckets[$key][] = $model;
434
            }
435
        }
436
437 163
        if ($checkMultiple && !$this->multiple) {
438 73
            foreach ($buckets as $i => $bucket) {
439 73
                $buckets[$i] = reset($bucket);
440
            }
441
        }
442
443 163
        return $buckets;
444
    }
445
446
    /**
447
     * @param array $map
448
     * @param array $viaMap
449
     * @return array
450
     */
451 5
    private function mapVia($map, $viaMap) {
452 5
        $resultMap = [];
453 5
        foreach ($map as $key => $linkKeys) {
454 5
            foreach (array_keys($linkKeys) as $linkKey) {
455 5
                $resultMap[$key] = $viaMap[$linkKey];
456
            }
457
        }
458 5
        return $resultMap;
459
    }
460
461
    /**
462
     * Indexes buckets by column name.
463
     *
464
     * @param array $buckets
465
     * @param string|callable $indexBy the name of the column by which the query results should be indexed by.
466
     * This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data.
467
     * @return array
468
     */
469 25
    private function indexBuckets($buckets, $indexBy)
470
    {
471 25
        $result = [];
472 25
        foreach ($buckets as $key => $models) {
473 25
            $result[$key] = [];
474 25
            foreach ($models as $model) {
475 25
                $index = is_string($indexBy) ? $model[$indexBy] : call_user_func($indexBy, $model);
476 25
                $result[$key][$index] = $model;
477
            }
478
        }
479
480 25
        return $result;
481
    }
482
483
    /**
484
     * @param array $attributes the attributes to prefix
485
     * @return array
486
     */
487 359
    private function prefixKeyColumns($attributes)
488
    {
489 359
        if ($this instanceof ActiveQuery && (!empty($this->join) || !empty($this->joinWith))) {
490 50
            if (empty($this->from)) {
491
                /* @var $modelClass ActiveRecord */
492 15
                $modelClass = $this->modelClass;
493 15
                $alias = $modelClass::tableName();
494
            } else {
495 45
                foreach ($this->from as $alias => $table) {
496 45
                    if (!is_string($alias)) {
497 45
                        $alias = $table;
498
                    }
499 45
                    break;
500
                }
501
            }
502 50
            if (isset($alias)) {
503 50
                foreach ($attributes as $i => $attribute) {
504 50
                    $attributes[$i] = "$alias.$attribute";
505
                }
506
            }
507
        }
508
509 359
        return $attributes;
510
    }
511
512
    /**
513
     * @param array $models
514
     */
515 359
    private function filterByModels($models)
516
    {
517 359
        $attributes = array_keys($this->link);
518
519 359
        $attributes = $this->prefixKeyColumns($attributes);
520
521 359
        $values = [];
522 359
        if (count($attributes) === 1) {
523
            // single key
524 349
            $attribute = reset($this->link);
525 349
            foreach ($models as $model) {
526 349
                if (($value = $model[$attribute]) !== null) {
527 344
                    if (is_array($value)) {
528
                        $values = array_merge($values, $value);
529 344
                    } elseif ($value instanceof ArrayExpression && $value->getDimension() === 1) {
530
                        $values = array_merge($values, $value->getValue());
531
                    } else {
532 349
                        $values[] = $value;
533
                    }
534
                }
535
            }
536 349
            if (empty($values)) {
537 349
                $this->emulateExecution();
538
            }
539
        } else {
540
            // composite keys
541
542
            // ensure keys of $this->link are prefixed the same way as $attributes
543 15
            $prefixedLink = array_combine($attributes, $this->link);
544 15
            foreach ($models as $model) {
545 15
                $v = [];
546 15
                foreach ($prefixedLink as $attribute => $link) {
547 15
                    $v[$attribute] = $model[$link];
548
                }
549 15
                $values[] = $v;
550 15
                if (empty($v)) {
551 15
                    $this->emulateExecution();
552
                }
553
            }
554
        }
555
556 359
        if (!empty($values)) {
557 354
            $scalarValues = [];
558 354
            $nonScalarValues = [];
559 354
            foreach ($values as $value) {
560 354
                if (is_scalar($value)) {
561 344
                    $scalarValues[] = $value;
562
                } else {
563 354
                    $nonScalarValues[] = $value;
564
                }
565
            }
566
567 354
            $scalarValues = array_unique($scalarValues);
568 354
            $values = array_merge($scalarValues, $nonScalarValues);
569
        }
570
571 359
        $this->andWhere(['in', $attributes, $values]);
572 359
    }
573
574
    /**
575
     * @param ActiveRecordInterface|array $model
576
     * @param array $attributes
577
     * @return string
578
     */
579 163
    private function getModelKey($model, $attributes)
580
    {
581 163
        $key = [];
582 163
        foreach ($attributes as $attribute) {
583 163
            $key[] = $this->normalizeModelKey($model[$attribute]);
584
        }
585 163
        if (count($key) > 1) {
586 5
            return serialize($key);
587
        }
588 158
        return reset($key);
589
    }
590
591
    /**
592
     * @param mixed $value raw key value. Since 2.0.40 non-string values must be convertable to string (like special
593
     * objects for cross-DBMS relations, for example: `|MongoId`).
594
     * @return string normalized key value.
595
     */
596 163
    private function normalizeModelKey($value)
597
    {
598
        try {
599 163
            return (string)$value;
600
        } catch (\Exception $e) {
601
            throw new InvalidConfigException('Value must be convertable to string.');
602
        } catch (\Throwable $e) {
603
            throw new InvalidConfigException('Value must be convertable to string.');
604
        }
605
    }
606
607
    /**
608
     * @param array $primaryModels either array of AR instances or arrays
609
     * @return array
610
     */
611 35
    private function findJunctionRows($primaryModels)
612
    {
613 35
        if (empty($primaryModels)) {
614
            return [];
615
        }
616 35
        $this->filterByModels($primaryModels);
617
        /* @var $primaryModel ActiveRecord */
618 35
        $primaryModel = reset($primaryModels);
619 35
        if (!$primaryModel instanceof ActiveRecordInterface) {
620
            // when primaryModels are array of arrays (asArray case)
621
            $primaryModel = $this->modelClass;
622
        }
623
624 35
        return $this->asArray()->all($primaryModel::getDb());
625
    }
626
}
627