Load keys for BelongsTo.
@param Collection $relations
@param BelongsTo $relationClass
@param Model $relationModel
@param Model $model
@param Builder $query
@param $direction
322704
protected function loadBelongsTo(
        Collection $relations,
        BelongsTo $relationClass,
        Model $relationModel,
        Model $model,
        Builder $query,
        $direction
    ) {
        $foreignKey = $relationClass->getOwnerKey();
        $ownerKey = $relationClass->getForeignKey();

        $ownerTable = $model->getTable();
        $foreignTable = $relationModel->getTable();

        $ownerColumn = implode('.', [$ownerTable, $ownerKey]);
        $foreignColumn = implode('.', [$foreignTable, $foreignKey]);
        $sortedColumnRaw = '`'.$foreignTable.'`.`'.$relations->last().'`';
        $sortedColumnAlias = implode('__', [$foreignTable, $relations->last()]);

        $this->sortedColumnAlias = $sortedColumnAlias;

        $query
            ->addSelect([DB::raw($sortedColumnRaw.' AS '.$sortedColumnAlias)])
            ->join($foreignTable, $foreignColumn, '=', $ownerColumn, 'left');
    }
526826
protected function addToQueue($object, $relations)
	{
		if( ! array_key_exists($object->type, self::$loadQueue) )
		{
			self::$loadQueue[$object->type] = [];
		}
		$relationsKey = base64_encode(json_encode($relations));
		if( ! array_key_exists($relationsKey, self::$loadQueue[$object->type]) )
		{
			self::$loadQueue[$object->type][$relationsKey] = [ 'type' => $object->type, 'ids' => [], 'relations' => $relations ];
		}
		self::$loadQueue[$object->type][$relationsKey]['ids'][] = $object->id;

	}
579967
protected function parseRelations(array $relations)
	{
		$results = array();

		foreach ($relations as $name => $constraints)
		{
			// If the "relation" value is actually a numeric key, we can assume that no
			// constraints have been specified for the eager load and we'll just put
			// an empty Closure with the loader so that we can treat all the same.
			if (is_numeric($name))
			{
				$f = function() {};

				list($name, $constraints) = array($constraints, $f);
			}

			// We need to separate out any nested includes. Which allows the developers
			// to load deep relationships using "dots" without stating each level of
			// the relationship with its own key in the array of eager load names.
			$results = $this->parseNested($name, $results);

			$results[$name] = $constraints;
		}

		return $results;
	}
1021828
protected function updateRelation($relationsData)
    {
        foreach ($relationsData as $name => $values) {
            if (!method_exists($this->model, $name)) {
                continue;
            }

            $relation = $this->model->$name();

            $oneToOneRelation = $relation instanceof \Illuminate\Database\Eloquent\Relations\HasOne
                || $relation instanceof \Illuminate\Database\Eloquent\Relations\MorphOne;

            $prepared = $this->prepareUpdate([$name => $values], $oneToOneRelation);

            if (empty($prepared)) {
                continue;
            }

            switch (get_class($relation)) {
                case \Illuminate\Database\Eloquent\Relations\BelongsToMany::class:
                case \Illuminate\Database\Eloquent\Relations\MorphToMany::class:
                    if (isset($prepared[$name])) {
                        $relation->sync($prepared[$name]);
                    }
                    break;
                case \Illuminate\Database\Eloquent\Relations\HasOne::class:

                    $related = $this->model->$name;

                    // if related is empty
                    if (is_null($related)) {
                        $related = $relation->getRelated();
                        $related->{$relation->getForeignKeyName()} = $this->model->{$this->model->getKeyName()};
                    }

                    foreach ($prepared[$name] as $column => $value) {
                        $related->setAttribute($column, $value);
                    }

                    $related->save();
                    break;
                case \Illuminate\Database\Eloquent\Relations\MorphOne::class:
                    $related = $this->model->$name;
                    if (is_null($related)) {
                        $related = $relation->make();
                    }
                    foreach ($prepared[$name] as $column => $value) {
                        $related->setAttribute($column, $value);
                    }
                    $related->save();
                    break;
                case \Illuminate\Database\Eloquent\Relations\HasMany::class:
                case \Illuminate\Database\Eloquent\Relations\MorphMany::class:

                    foreach ($prepared[$name] as $related) {
                        $relation = $this->model()->$name();

                        $keyName = $relation->getRelated()->getKeyName();

                        $instance = $relation->findOrNew(array_get($related, $keyName));

                        if ($related[static::REMOVE_FLAG_NAME] == 1) {
                            $instance->delete();

                            continue;
                        }

                        array_forget($related, static::REMOVE_FLAG_NAME);

                        $instance->fill($related);

                        $instance->save();
                    }

                    break;
            }
        }
    }
1003883
public function scopeWithout($query, $relations)
    {
        $relations = is_array($relations) ? $relations : array_slice(func_get_args(), 1);
        $relationships = array_dot($query->getEagerLoads());
        foreach ($relations as $relation) {
            unset($relationships[$relation]);
        }

        return $query->setEagerLoads([])->with(array_keys($relationships));
    }
1116260
public static function setRelations($modelOne, $modelTwo, $relations): void
    {
        $name = [$modelOne, $modelTwo];
        sort($name);
        $name = implode(':', $name);
        // create record in static variable
        self::$relations[$name] = $relations;
    }
1326946
protected function associateRelationModels(string $relationName, EloquentCollection $relationModels): self
    {
        $relation = $this->getRelationInstance($relationName);

        $relation->match(
            $this->models->all(),
            $relationModels,
            $relationName
        );

        return $this;
    }
883292
public function loadRelations() {
        foreach ([
            Relation::MANY_TO_ONE => $this->belongsTo,
            Relation::MANY_TO_MANY => $this->belongsToMany,
            Relation::ONE_TO_ONE => $this->hasOne,
            Relation::ONE_TO_MANY => $this->hasMany
        ] as $type => $relations) {
            foreach ($relations as $alias => $relation) {
                if (is_string($relation)) {
                    $relation = ['model' => $relation];
                }

                $relation = $relation + [
                    'model' => null,
                    'foreignKey' => null,
                    'relatedForeignKey' => null,
                    'conditions' => null,
                    'junction' => null
                ];

                switch ($type) {
                    case Relation::MANY_TO_ONE:
                        $this->belongsTo($alias, $relation['model'], $relation['foreignKey'], $relation['conditions']);
                    break;
                    case Relation::MANY_TO_MANY:
                        $this->belongsToMany($alias, $relation['model'], $relation['junction'], $relation['foreignKey'], $relation['relatedForeignKey'], $relation['conditions']);
                    break;
                    case Relation::ONE_TO_ONE:
                        $this->hasOne($alias, $relation['model'], $relation['relatedForeignKey'], $relation['conditions']);
                    break;
                    case Relation::ONE_TO_MANY:
                        $this->hasMany($alias, $relation['model'], $relation['relatedForeignKey'], $relation['conditions']);
                    break;
                }
            }
        }

        return $this;
    }
1089640
protected function parseWithRelations(array $relations)
    {
        $results = [];

        foreach ($relations as $name => $constraints) {
            // If the "relation" value is actually a numeric key, we can assume that no
            // constraints have been specified for the eager load and we'll just put
            // an empty Closure with the loader so that we can treat all the same.
            if (is_numeric($name)) {
                $name = $constraints;

                list($name, $constraints) = (mb_strpos($name, ':') !== false)
                            ? $this->createSelectWithConstraint($name)
                            : [$name, function () {
                                //
                            }];
            }

            // We need to separate out any nested includes. Which allows the developers
            // to load deep relationships using "dots" without stating each level of
            // the relationship with its own key in the array of eager load names.
            $results = $this->addNestedWiths($name, $results);

            $results[$name] = $constraints;
        }

        return $results;
    }
804743
public function match(array $models, Collection $results, $relation)
    {
        $foreign = $this->foreignKey;

        $other = $this->otherKey;

        $dictionary = array();

        foreach ($results as $result) {
            $dictionary[$result->getAttribute($other)] = $result;
        }

        foreach ($models as $model) {
            if (isset($dictionary[$model->$foreign])) {
                $model->setRelation($relation, $dictionary[$model->$foreign]);
            }
        }

        return $models;
    }
670698
public function match(array $models, Collection $results, $relation)
    {
        $foreign = $this->foreignKey;

        $owner = $this->ownerKey;

        // First we will get to build a dictionary of the child models by their primary
        // key of the relationship, then we can easily match the children back onto
        // the parents using that dictionary and the primary key of the children.
        $dictionary = [];

        foreach ($results as $result) {
            if (is_array($owner)) { //Check for multi-columns relationship
                $dictKeyValues = array_map(function ($k) use ($result) {
                    return $result->{$k};
                }, $owner);

                $dictionary[implode('-', $dictKeyValues)] = $result;
            } else {
                $dictionary[$result->getAttribute($owner)] = $result;
            }
        }

        // Once we have the dictionary constructed, we can loop through all the parents
        // and match back onto their children using these keys of the dictionary and
        // the primary key of the children to map them onto the correct instances.
        foreach ($models as $model) {
            if (is_array($foreign)) { //Check for multi-columns relationship
                $dictKeyValues = array_map(function ($k) use ($model) {
                    return $model->{$k};
                }, $foreign);

                $key = implode('-', $dictKeyValues);
            } else {
                $key = $model->{$foreign};
            }

            if (isset($dictionary[$key])) {
                $model->setRelation($relation, $dictionary[$key]);
            }
        }

        return $models;
    }
160794
public function initRelation(array $models, $relation)
    {
        foreach ($models as $model) {
            $model->setRelation($relation, $this->getDefaultFor($model));
        }

        return $models;
    }
390805
public function edgeFromRelationWithDirection(Relationship $relation, Model $parent, Model $related, $direction)
    {
        // If the direction is of type 'any' we need to figure out the relationship direction
        // from the determined relation.
        if ($direction == 'any')
        {
            $direction = $this->directionFromRelation($relation, $parent, $related);
        }

        // Based on the direction we are now able to construct the edge class name and call for
        // an instance of it then pass it the actual relationship that was previously found.
        $class = $this->getEdgeClass($direction);
        $edge = new $class($this->query, $parent, $related, $relation->getType());
        $edge->setRelation($relation, true);

        return $edge;
    }
683554
function with(array $relations, array $where = null, $order = null, $limit = 0, $offset = 0) {
		$qthis = $this->conn->quoteName($this->getName());
		$query = $this->getQueryWriter()->reset();
		$query->write("SELECT", "$qthis.*", "FROM", $qthis);
		foreach ($relations as $relation) {
			if (!($relation instanceof Table\Reference)) {
				$relation = static::resolve($relation)->getRelation($this->getName());
			}
			if ($this->getName() === $relation->foreignTable) {
				$query->write("JOIN", $relation->referencedTable)->write("ON");
				foreach ($relation as $key => $ref) {
					$query->criteria(
						array(
							"{$relation->referencedTable}.{$ref}=" => 
								new QueryExpr("{$relation->foreignTable}.{$key}")
						)
					);
				}
			} else {
				$query->write("JOIN", $relation->foreignTable)->write("ON");
				foreach ($relation as $key => $ref) {
					$query->criteria(
						array(
							"{$relation->referencedTable}.{$ref}=" => 
								new QueryExpr("{$relation->foreignTable}.{$key}")
						)
					);
				}
			}
		}
		if ($where) {
			$query->write("WHERE")->criteria($where);
		}
		if ($order) {
			$query->write("ORDER BY", $order);
		}
		if ($limit) {
			$query->write("LIMIT", $limit);
		}
		if ($offset) {
			$query->write("OFFSET", $offset);
		}
		return $this->execute($query);
	}
1290096
public function loadCount($relations)
    {
        $relations = is_string($relations) ? func_get_args() : $relations;

        $this->newCollection([$this])->loadCount($relations);

        return $this;
    }
520382
protected function loadRelation(array $results, string $name, Closure $constraints) : array
    {
        // First we will "back up" the existing where conditions on the query so we can
        // add our eager constraints. Then we will merge the wheres that were on the
        // query back to it in order that any where conditions might be specified.
        $relation = $this->getRelation($name);

        $relation->addEagerConstraints($results);

        call_user_func($constraints, $relation);

        // Once we have the results, we just match those back up to their parent models
        // using the relationship instance. Then we just return the finished arrays
        // of models which have been eagerly hydrated and are readied for return.
        return $relation->match($results, $name);
    }
691130
public function load($relations)
    {
        if ($this->isNotEmpty()) {
            if (is_string($relations)) {
                $relations = func_get_args();
            }

            $query = $this->first()->newQueryWithoutRelationships()->with($relations);

            $this->items = $query->eagerLoadRelations($this->items);
        }

        return $this;
    }