ActiveRelationTrait.php 19.4 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\db;
9 10

use yii\base\InvalidConfigException;
11
use yii\base\InvalidParamException;
12 13

/**
14
 * ActiveRelationTrait implements the common methods and properties for active record relational queries.
15 16
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
17
 * @author Carsten Brandt <mail@cebe.cc>
18
 * @since 2.0
19
 *
20 21
 * @method ActiveRecordInterface one()
 * @method ActiveRecordInterface[] all()
22
 * @property ActiveRecord $modelClass
23
 */
24
trait ActiveRelationTrait
25
{
26 27 28
    /**
     * @var boolean whether this query represents a relation to more than one record.
     * This property is only used in relational context. If true, this relation will
29 30
     * populate all query results into AR instances using [[Query::all()|all()]].
     * If false, only the first row of the results will be retrieved using [[Query::one()|one()]].
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
     */
    public $multiple;
    /**
     * @var ActiveRecord the primary model of a relational query.
     * This is used only in lazy loading with dynamic query options.
     */
    public $primaryModel;
    /**
     * @var array the columns of the primary and foreign tables that establish a relation.
     * The array keys must be columns of the table for this relation, and the array values
     * must be the corresponding columns from the primary table.
     * Do not prefix or quote the column names as this will be done automatically by Yii.
     * This property is only used in relational context.
     */
    public $link;
    /**
47
     * @var array|object the query associated with the junction table. Please call [[via()]]
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
     * to set this property instead of directly setting it.
     * This property is only used in relational context.
     * @see via()
     */
    public $via;
    /**
     * @var string the name of the relation that is the inverse of this relation.
     * For example, an order has a customer, which means the inverse of the "customer" relation
     * is the "orders", and the inverse of the "orders" relation is the "customer".
     * If this property is set, the primary record(s) will be referenced through the specified relation.
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
     * and accessing the customer of an order will not trigger new DB query.
     * This property is only used in relational context.
     * @see inverseOf()
     */
    public $inverseOf;

65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    /**
     * Clones internal objects.
     */
    public function __clone()
    {
        parent::__clone();
        // make a clone of "via" object so that the same query object can be reused multiple times
        if (is_object($this->via)) {
            $this->via = clone $this->via;
        } elseif (is_array($this->via)) {
            $this->via = [$this->via[0], clone $this->via[1]];
        }
    }

    /**
81
     * Specifies the relation associated with the junction table.
82 83 84 85 86 87 88 89 90 91 92 93
     *
     * Use this method to specify a pivot record/table when declaring a relation in the [[ActiveRecord]] class:
     *
     * ```php
     * public function getOrders()
     * {
     *     return $this->hasOne(Order::className(), ['id' => 'order_id']);
     * }
     *
     * public function getOrderItems()
     * {
     *     return $this->hasMany(Item::className(), ['id' => 'item_id'])
94
     *                 ->via('orders');
95 96 97
     * }
     * ```
     *
98
     * @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
99
     * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
100 101
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
     * @return static the relation object itself.
102
     */
103
    public function via($relationName, callable $callable = null)
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    {
        $relation = $this->primaryModel->getRelation($relationName);
        $this->via = [$relationName, $relation];
        if ($callable !== null) {
            call_user_func($callable, $relation);
        }
        return $this;
    }

    /**
     * Sets the name of the relation that is the inverse of this relation.
     * For example, an order has a customer, which means the inverse of the "customer" relation
     * is the "orders", and the inverse of the "orders" relation is the "customer".
     * If this property is set, the primary record(s) will be referenced through the specified relation.
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
     * and accessing the customer of an order will not trigger a new DB query.
     *
     * Use this method when declaring a relation in the [[ActiveRecord]] class:
     *
     * ```php
     * public function getOrders()
     * {
     *     return $this->hasMany(Order::className(), ['customer_id' => 'id'])->inverseOf('customer');
     * }
     * ```
     *
130
     * @param string $relationName the name of the relation that is the inverse of this relation.
131 132 133 134 135 136 137 138 139 140 141
     * @return static the relation object itself.
     */
    public function inverseOf($relationName)
    {
        $this->inverseOf = $relationName;
        return $this;
    }

    /**
     * Finds the related records for the specified primary record.
     * This method is invoked when a relation of an ActiveRecord is being accessed in a lazy fashion.
142 143 144 145
     * @param string $name the relation name
     * @param ActiveRecordInterface|BaseActiveRecord $model the primary model
     * @return mixed the related record(s)
     * @throws InvalidParamException if the relation is invalid
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
     */
    public function findFor($name, $model)
    {
        if (method_exists($model, 'get' . $name)) {
            $method = new \ReflectionMethod($model, 'get' . $name);
            $realName = lcfirst(substr($method->getName(), 3));
            if ($realName !== $name) {
                throw new InvalidParamException('Relation names are case sensitive. ' . get_class($model) . " has a relation named \"$realName\" instead of \"$name\".");
            }
        }

        $related = $this->multiple ? $this->all() : $this->one();

        if ($this->inverseOf === null || empty($related)) {
            return $related;
        }

        $inverseRelation = (new $this->modelClass)->getRelation($this->inverseOf);

        if ($this->multiple) {
            foreach ($related as $i => $relatedModel) {
                if ($relatedModel instanceof ActiveRecordInterface) {
                    $relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$model] : $model);
                } else {
                    $related[$i][$this->inverseOf] = $inverseRelation->multiple ? [$model] : $model;
                }
            }
        } else {
            if ($related instanceof ActiveRecordInterface) {
                $related->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$model] : $model);
            } else {
                $related[$this->inverseOf] = $inverseRelation->multiple ? [$model] : $model;
            }
        }

        return $related;
    }

    /**
     * Finds the related records and populates them into the primary models.
186 187 188
     * @param string $name the relation name
     * @param array $primaryModels primary models
     * @return array the related models
189 190 191 192 193 194 195 196 197
     * @throws InvalidConfigException if [[link]] is invalid
     */
    public function populateRelation($name, &$primaryModels)
    {
        if (!is_array($this->link)) {
            throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
        }

        if ($this->via instanceof self) {
198
            // via junction table
199
            /* @var $viaQuery ActiveRelationTrait */
200
            $viaQuery = $this->via;
201
            $viaModels = $viaQuery->findJunctionRows($primaryModels);
202 203 204
            $this->filterByModels($viaModels);
        } elseif (is_array($this->via)) {
            // via relation
205
            /* @var $viaQuery ActiveRelationTrait|ActiveQueryTrait */
206
            list($viaName, $viaQuery) = $this->via;
207 208 209 210
            if ($viaQuery->asArray === null) {
                // inherit asArray from primary query
                $viaQuery->asArray($this->asArray);
            }
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
            $viaQuery->primaryModel = null;
            $viaModels = $viaQuery->populateRelation($viaName, $primaryModels);
            $this->filterByModels($viaModels);
        } else {
            $this->filterByModels($primaryModels);
        }

        if (count($primaryModels) === 1 && !$this->multiple) {
            $model = $this->one();
            foreach ($primaryModels as $i => $primaryModel) {
                if ($primaryModel instanceof ActiveRecordInterface) {
                    $primaryModel->populateRelation($name, $model);
                } else {
                    $primaryModels[$i][$name] = $model;
                }
                if ($this->inverseOf !== null) {
                    $this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf);
                }
            }

            return [$model];
        } else {
233 234 235 236
            // https://github.com/yiisoft/yii2/issues/3197
            // delay indexing related models after buckets are built
            $indexBy = $this->indexBy;
            $this->indexBy = null;
237
            $models = $this->all();
238

239 240 241 242 243 244
            if (isset($viaModels, $viaQuery)) {
                $buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery->link);
            } else {
                $buckets = $this->buildBuckets($models, $this->link);
            }

245 246 247 248 249
            $this->indexBy = $indexBy;
            if ($this->indexBy !== null && $this->multiple) {
                $buckets = $this->indexBuckets($buckets, $this->indexBy);
            }

250 251
            $link = array_values(isset($viaQuery) ? $viaQuery->link : $this->link);
            foreach ($primaryModels as $i => $primaryModel) {
Carsten Brandt committed
252
                if ($this->multiple && count($link) == 1 && is_array($keys = $primaryModel[reset($link)])) {
253 254
                    $value = [];
                    foreach ($keys as $key) {
255 256 257
                        if (!is_scalar($key)) {
                            $key = serialize($key);
                        }
258
                        if (isset($buckets[$key])) {
259 260 261 262 263 264 265 266
                            if ($this->indexBy !== null) {
                                // if indexBy is set, array_merge will cause renumbering of numeric array
                                foreach($buckets[$key] as $bucketKey => $bucketValue) {
                                    $value[$bucketKey] = $bucketValue;
                                }
                            } else {
                                $value = array_merge($value, $buckets[$key]);
                            }
267 268 269 270 271 272
                        }
                    }
                } else {
                    $key = $this->getModelKey($primaryModel, $link);
                    $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null);
                }
273 274 275 276 277 278 279 280 281 282 283 284 285 286
                if ($primaryModel instanceof ActiveRecordInterface) {
                    $primaryModel->populateRelation($name, $value);
                } else {
                    $primaryModels[$i][$name] = $value;
                }
            }
            if ($this->inverseOf !== null) {
                $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
            }

            return $models;
        }
    }

287 288 289 290 291 292
    /**
     * @param ActiveRecordInterface[] $primaryModels primary models
     * @param ActiveRecordInterface[] $models models
     * @param string $primaryName the primary relation name
     * @param string $name the relation name
     */
293 294 295 296 297 298
    private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name)
    {
        if (empty($models) || empty($primaryModels)) {
            return;
        }
        $model = reset($models);
299
        /* @var $relation ActiveQueryInterface|ActiveQuery */
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        $relation = $model instanceof ActiveRecordInterface ? $model->getRelation($name) : (new $this->modelClass)->getRelation($name);

        if ($relation->multiple) {
            $buckets = $this->buildBuckets($primaryModels, $relation->link, null, null, false);
            if ($model instanceof ActiveRecordInterface) {
                foreach ($models as $model) {
                    $key = $this->getModelKey($model, $relation->link);
                    $model->populateRelation($name, isset($buckets[$key]) ? $buckets[$key] : []);
                }
            } else {
                foreach ($primaryModels as $i => $primaryModel) {
                    if ($this->multiple) {
                        foreach ($primaryModel as $j => $m) {
                            $key = $this->getModelKey($m, $relation->link);
                            $primaryModels[$i][$j][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
                        }
                    } elseif (!empty($primaryModel[$primaryName])) {
                        $key = $this->getModelKey($primaryModel[$primaryName], $relation->link);
                        $primaryModels[$i][$primaryName][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
                    }
                }
            }
        } else {
            if ($this->multiple) {
                foreach ($primaryModels as $i => $primaryModel) {
                    foreach ($primaryModel[$primaryName] as $j => $m) {
                        if ($m instanceof ActiveRecordInterface) {
                            $m->populateRelation($name, $primaryModel);
                        } else {
                            $primaryModels[$i][$primaryName][$j][$name] = $primaryModel;
                        }
                    }
                }
            } else {
                foreach ($primaryModels as $i => $primaryModel) {
                    if ($primaryModels[$i][$primaryName] instanceof ActiveRecordInterface) {
                        $primaryModels[$i][$primaryName]->populateRelation($name, $primaryModel);
                    } elseif (!empty($primaryModels[$i][$primaryName])) {
                        $primaryModels[$i][$primaryName][$name] = $primaryModel;
                    }
                }
            }
        }
    }

    /**
346 347 348 349 350
     * @param array $models
     * @param array $link
     * @param array $viaModels
     * @param array $viaLink
     * @param boolean $checkMultiple
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
     * @return array
     */
    private function buildBuckets($models, $link, $viaModels = null, $viaLink = null, $checkMultiple = true)
    {
        if ($viaModels !== null) {
            $map = [];
            $viaLinkKeys = array_keys($viaLink);
            $linkValues = array_values($link);
            foreach ($viaModels as $viaModel) {
                $key1 = $this->getModelKey($viaModel, $viaLinkKeys);
                $key2 = $this->getModelKey($viaModel, $linkValues);
                $map[$key2][$key1] = true;
            }
        }

        $buckets = [];
        $linkKeys = array_keys($link);

        if (isset($map)) {
            foreach ($models as $i => $model) {
                $key = $this->getModelKey($model, $linkKeys);
                if (isset($map[$key])) {
                    foreach (array_keys($map[$key]) as $key2) {
374
                        $buckets[$key2][] = $model;
375 376 377 378 379 380
                    }
                }
            }
        } else {
            foreach ($models as $i => $model) {
                $key = $this->getModelKey($model, $linkKeys);
381
                $buckets[$key][] = $model;
382 383 384 385 386 387 388 389 390 391 392 393
            }
        }

        if ($checkMultiple && !$this->multiple) {
            foreach ($buckets as $i => $bucket) {
                $buckets[$i] = reset($bucket);
            }
        }

        return $buckets;
    }

394 395 396 397 398 399 400 401 402

    /**
     * Indexes buckets by column name.
     *
     * @param array $buckets
     * @var string|callable $column the name of the column by which the query results should be indexed by.
     * This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data.
     * @return array
     */
403 404 405 406 407 408 409 410 411 412 413 414 415
    private function indexBuckets($buckets, $indexBy)
    {
        $result = [];
        foreach ($buckets as $key => $models) {
            $result[$key] = [];
            foreach ($models as $model) {
                $index = is_string($indexBy) ? $model[$indexBy] : call_user_func($indexBy, $model);
                $result[$key][$index] = $model;
            }
        }
        return $result;
    }

Carsten Brandt committed
416 417 418 419
    /**
     * @param array $attributes the attributes to prefix
     * @return array
     */
420 421 422 423
    private function prefixKeyColumns($attributes)
    {
        if ($this instanceof ActiveQuery && (!empty($this->join) || !empty($this->joinWith))) {
            if (empty($this->from)) {
424
                /* @var $modelClass ActiveRecord */
425 426 427 428 429 430 431 432 433 434 435 436
                $modelClass = $this->modelClass;
                $alias = $modelClass::tableName();
            } else {
                foreach ($this->from as $alias => $table) {
                    if (!is_string($alias)) {
                        $alias = $table;
                    }
                    break;
                }
            }
            if (isset($alias)) {
                foreach ($attributes as $i => $attribute) {
Carsten Brandt committed
437
                    $attributes[$i] = "$alias.$attribute";
438 439 440 441 442 443
                }
            }
        }
        return $attributes;
    }

444 445 446 447 448 449
    /**
     * @param array $models
     */
    private function filterByModels($models)
    {
        $attributes = array_keys($this->link);
450 451 452

        $attributes = $this->prefixKeyColumns($attributes);

453 454 455 456 457 458
        $values = [];
        if (count($attributes) === 1) {
            // single key
            $attribute = reset($this->link);
            foreach ($models as $model) {
                if (($value = $model[$attribute]) !== null) {
459 460 461 462 463
                    if (is_array($value)) {
                        $values = array_merge($values, $value);
                    } else {
                        $values[] = $value;
                    }
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
                }
            }
        } else {
            // composite keys
            foreach ($models as $model) {
                $v = [];
                foreach ($this->link as $attribute => $link) {
                    $v[$attribute] = $model[$link];
                }
                $values[] = $v;
            }
        }
        $this->andWhere(['in', $attributes, array_unique($values, SORT_REGULAR)]);
    }

    /**
480 481
     * @param ActiveRecord|array $model
     * @param array $attributes
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
     * @return string
     */
    private function getModelKey($model, $attributes)
    {
        if (count($attributes) > 1) {
            $key = [];
            foreach ($attributes as $attribute) {
                $key[] = $model[$attribute];
            }

            return serialize($key);
        } else {
            $attribute = reset($attributes);
            $key = $model[$attribute];

            return is_scalar($key) ? $key : serialize($key);
        }
    }

    /**
502
     * @param array $primaryModels either array of AR instances or arrays
503 504
     * @return array
     */
505
    private function findJunctionRows($primaryModels)
506 507 508 509 510
    {
        if (empty($primaryModels)) {
            return [];
        }
        $this->filterByModels($primaryModels);
511
        /* @var $primaryModel ActiveRecord */
512 513 514 515 516 517 518 519
        $primaryModel = reset($primaryModels);
        if (!$primaryModel instanceof ActiveRecordInterface) {
            // when primaryModels are array of arrays (asArray case)
            $primaryModel = new $this->modelClass;
        }

        return $this->asArray()->all($primaryModel->getDb());
    }
520
}