Initialize the relation on a set of models.

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

        return $models;
    }
325518
public function createWith(array $attributes, array $relations) {
        // Collect the model attributes and label in the form of ['label' => $label, 'attributes' => $attributes]
        // as expected by the Query Builder.
        $attributes = $this->prepareForCreation($this->model, $attributes);
        $model = ['label' => $this->model->getTable(), 'attributes' => $attributes];

        /**
         * Collect the related models in the following for as expected by the Query Builder:
         *
         *  [
         *       'label' => ['Permission'],
         *       'relation' => [
         *           'name' => 'photos',
         *           'type' => 'PHOTO',
         *           'direction' => 'out',
         *       ],
         *       'values' => [
         *           // A mix of models and attributes, doesn't matter really..
         *           ['url' => '', 'caption' => ''],
         *           ['url' => '', 'caption' => '']
         *       ]
         *  ]
         */
        $related = [];
        foreach ($relations as $relation => $values) {
            $name = $relation;
            // Get the relation by calling the model's relationship function.
            if (!method_exists($this->model, $relation))
                throw new QueryException("The relation method $relation() does not exist on " . get_class($this->model));

            $relationship = $this->model->$relation();
            // Bring the model from the relationship.
            $relatedModel = $relationship->getRelated();

            // We will first check to see what the dev have passed as values
            // so that we make sure that we have an array moving forward
            // In the case of a model Id or an associative array or a Model instance it means that
            // this is probably a One-To-One relationship or the dev decided not to add
            // multiple records as relations so we'll wrap it up in an array.
            if (!is_array($values) || Helpers::isAssocArray($values) || $values instanceof Model)
                $values = [$values];

            $label = $relationship->getRelated()->getTable();
            $direction = $relationship->getEdgeDirection();
            $type = $relationship->getRelationType();

            // Hold the models that we need to attach
            $attach = [];
            // Hold the models that we need to create
            $create = [];
            // Separate the models that needs to be attached from the ones that needs
            // to be created.
            foreach ($values as $value) {
                // If this is a Model then the $exists property will indicate what we need
                // so we'll add its id to be attached.
                if ($value instanceof Model and $value->exists === true) {
                    $attach[] = $value->getKey();
                }
                // Next we will check whether we got a Collection in so that we deal with it
                // accordingly, which guarantees sending an Eloquent result straight in would work.
                elseif ($value instanceof Collection) {
                    $attach = array_merge($attach, $value->lists('id'));
                }
                // Or in the case where the attributes are neither an array nor a model instance
                // then this is assumed to be the model Id that the dev means to attach and since
                // Orientdb node Ids are always an int then we take that as a value.
                elseif (!is_array($value) && !$value instanceof Model) {
                    $attach[] = intval($value);
                }
                // In this case the record is considered to be new to the market so let's create it.
                else
                    $create[] = $this->prepareForCreation($relatedModel, $value);
            }

            $relation = compact('name', 'type', 'direction');
            $related[] = compact('relation', 'label', 'create', 'attach');
        }

        $result = $this->query->createWith($model, $related);

        $models = $this->resultsToModels($this->model->getConnectionName(), $result);
        return (!empty($models)) ? reset($models) : null;
    }
68738
public function addRelation($relation)
    {
        $relations = $this->getRelations();
        array_push($relations, $relation);
        $this->setRelations($relations);
    }
106795
public function initRelation(array $models, $relation)
    {
        foreach ($models as $model)
        {
            // In the case of fetching nested relations, we will get an array
            // with the first key being the model we need, and the other being
            // the related model so we'll just take the first model out of the array.
            if (is_array($model)) $model = reset($model);

            $model->setRelation($relation, $this->related->newCollection());
        }

        return $models;
    }
1153960
protected function getResultsByRelatedKey($relations)
	{
		$resultsByRelatedKey = [];

		foreach ($relations as $relation)
		{
			if (!isset($resultsByRelatedKey[$relation->{$this->associativeLocal}]))
			{
				$resultsByRelatedKey[$relation->{$this->associativeLocal}] = new Rows;
			}

			$resultsByRelatedKey[$relation->{$this->associativeLocal}]->push($relation);
		}

		return $resultsByRelatedKey;
	}
566768
public static function create($models, array $relations) {
        $is_one = !static::isSomeArr($models);
        if ($is_one) {
            $models = [$models];
        }
        foreach ($relations as $key => $relation) {
            $relation = static::parse($relation, $key);
            $models =  $relation->getWithMulti($models);
        }
        return $is_one ? reset($models) : $models;
    }
650952
protected function getRelationNameFromRelationInstance(Relation $relation)
    {
        // Get all relations, load instances and compare them loosely
        foreach ($this->info->relations as $relationData) {

            if ($relation == $this->model()->{$relationData->method}()) {
                return $relationData->method;
            }
        }

        // @codeCoverageIgnoreStart
        return null;
        // @codeCoverageIgnoreEnd
    }
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;
    }
1290096
public function loadCount($relations)
    {
        $relations = is_string($relations) ? func_get_args() : $relations;

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

        return $this;
    }
377401
public function loadCount($relations)
    {
        if ($this->isEmpty()) {
            return $this;
        }

        $models = $this->first()->newModelQuery()
            ->whereKey($this->modelKeys())
            ->select($this->first()->getKeyName())
            ->withCount(...func_get_args())
            ->get();

        $attributes = Arr::except(
            array_keys($models->first()->getAttributes()),
            $models->first()->getKeyName()
        );

        $models->each(function ($model) use ($attributes) {
            $this->find($model->getKey())->forceFill(
                Arr::only($model->getAttributes(), $attributes)
            )->syncOriginalAttributes($attributes);
        });

        return $this;
    }
982029
public function newFromRelation(Relationship $relation)
    {
        $instance = new static($this->query, $this->parent, $this->related, $this->type, $this->attributes, $this->unique);

        $instance->setRelation($relation);

        return $instance;
    }
1308048
public function load($relations = [])
	{
		$this->addRelations($relations);
		
		$this->clearQueue();

		$this->queueUnresolvedObjects($this->data, $this->relations);

		$this->loadQueue();
	}
390427
public static function findRelation($row, $relation): array
    {
        $model = $row->getTable()->getModel();

        /** @var \Bluz\Db\Table $relationTable */
        $relationTable = self::getModelClass($relation);
        $relationTable::getInstance();

        if (!$relations = self::getRelations($model, $relation)) {
            throw new RelationNotFoundException(
                "Relations between model `$model` and `$relation` is not defined"
            );
        }

        // check many-to-many relations
        if (\count($relations) === 1) {
            $relations = self::getRelations($model, current($relations));
        }

        $field = $relations[$model];
        $key = $row->{$field};

        return self::findRelations($model, $relation, [$key]);
    }
994955
protected function getJoinKeys(Relation $relation)
    {
        if ($relation instanceof MorphTo) {
            throw new LogicException("MorphTo relation cannot be joined.");
        }

        if ($relation instanceof HasOneOrMany) {
            return [$relation->getQualifiedForeignKeyName(), $relation->getQualifiedParentKeyName()];
        }

        if ($relation instanceof BelongsTo) {
            return [$relation->getQualifiedForeignKeyName(), $relation->getQualifiedOwnerKeyName()];
        }

        if ($relation instanceof BelongsToMany) {
            return [$relation->getQualifiedRelatedPivotKeyName(), $relation->getRelated()->getQualifiedKeyName()];
        }

        if ($relation instanceof HasManyThrough) {
            $fk = $relation->getQualifiedFarKeyName();

            return [$fk, $relation->getParent()->getQualifiedKeyName()];
        }
    }
701682
protected function getNonExistingFromRelation(string $relation): array
    {
        $nonExisting = [];

        foreach ($this->relationships[$relation] as $aggregate) {
            if (!$aggregate->exists()) {
                $nonExisting[] = $aggregate;
            }
        }

        return $nonExisting;
    }
844222
protected function relationResolver($relation)
    {
        $return = ['relation' => '', 'action' => 'update'];

        try {
            list($relation, $action) = explode('@', $relation);
            $return = ['relation' => $relation, 'action' => $action];
        } catch (\Exception $e) {
            $return['relation'] = $relation;
        }

        if (!in_array($return['action'], $this->availableActions)) {
            DB::rollBack(); //Rollback the transaction before throw exception
            throw (new SoftCascadeNonExistentRelationActionException())->setRelation(implode('@', $return));
        }

        return $return;
    }
586032
protected function loadRelation(array $models, $name, Closure $constraints)
    {
        $relation = $this->getRelation($name);

        $relation->addEagerConstraints($models);

        call_user_func($constraints, $relation);

        $models = $relation->initRelation($models, $name);

        $results = $relation->getEager();

        return $relation->match($models, $results, $name);
    }