Finds (to be related) models by their keys.

@param string|Model    $model
@param array|Arrayable $keys
@return Collection|Model[]
971008
protected function getModelsByKey($model, $keys)
    {
        if (is_string($model)) {
            $model = new $model;
        }

        /** @var Model $model */
        return $model->withoutGlobalScopes()
            ->whereIn($model->getKeyName(), $keys)
            ->get()
            ->keyBy($model->getKeyName());
    }
282841
protected function getReferencesForModelKeys(array $keys, $targetModel = null)
    {
        $keys = array_filter($keys);

        if ( ! count($keys)) {
            return [];
        }

        $referenceData = $this->getReferenceDataProvider()->getForModelClassByType(
            $this->model,
            'form.field',
            $this->field->key(),
            $targetModel
        );

        if ( ! $referenceData) {
            return [];
        }

        $references = [];

        foreach ($keys as $key) {
            $references[ $key ] = $this->getReferenceRepository()
                ->getReferenceForModelMetaReferenceByKey($referenceData, $key);
        }

        return $references;
    }
103271
protected function appendRelatedModelsToModelData(array $model)
    {
        $relationships = array_merge(
            array_get($model, 'relationships.normal'),
            array_get($model, 'relationships.reverse')
        );

        $model['related_models'] = [];

        foreach ($relationships as $name => $relationship) {

            $relatedModelId = $relationship['model'];

            if (isset($model['related_models'][ $relatedModelId ])) continue;

            $model['related_models'][ $relatedModelId ] = $this->data['models'][ $relatedModelId ];
        }

        return $model;
    }
941371
protected function saveHasOneRelations(Model $model)
    {
        foreach ($model->getRelations() as $name => $relation) {
            if ($model->{$name}() instanceof HasOneOrMany && ! is_null($relation)) {
                if (is_array($relation) || $relation instanceof \Traversable) {
                    $model->{$name}()->saveMany($relation);
                } else {
                    $model->{$name}()->save($relation);
                }
            }
        }
    }
1001234
public function addEagerConstraints(array $models)
    {
        // We'll grab the primary key name of the related models since it could be set to
        // a non-standard name and not "id". We will then construct the constraint for
        // our eagerly loading query so it returns the proper models from execution.
        $key = $this->related->getTable().'.'.$this->ownerKey;

        $whereIn = $this->whereInMethod($this->related, $this->ownerKey);

        $this->query->{$whereIn}($key, $this->getEagerModelKeys($models));
    }
383584
protected function checkModels($related, $model)
    {
        if (!class_exists($related)) {
            $this->ModelNotFinded($related);
        }
        if (!class_exists(get_class($model))) {
            $this->ModelNotFinded(get_class($model));
        }
    }
886311
protected function getEagerModelKeys(array $models)
    {
        // First we need to gather all of the keys from the parent models so we know what
        // to query for via the eager loading query. We will add them to an array then
        // execute a "where in" statement to gather up all of those related records.
        $keys = collect($models)->map(function ($model) {
            return $model->{$this->foreignKey};
        })->filter()->all();

        // If there are no keys that were not null we will just return an array with either
        // null or 0 in (depending on if incrementing keys are in use) so the query wont
        // fail plus returns zero results, which should be what the developer expects.
        if (count($keys) === 0) {
            return [$this->relationHasIncrementingId() ? 0 : null];
        }

        return array_values(array_unique($keys));
    }
1341870
public static function getModelKeys($model, $includePrimary = true)
    {
        $keys = array_map(function ($foreignKey) {
            array_shift($foreignKey);
            return array_keys($foreignKey);
        }, $model->getTableSchema()->foreignKeys);
        if ($includePrimary) {
            $keys[] = $model->primaryKey();
        }
        return call_user_func_array('array_merge', $keys);
    }
963074
public function relatedKey($key, $model = false)
    {
        if (!$model) {
            $model = $this->model;
        }

        if (($methodBreaker = strpos($key, '.')) !== false) {
            $method = substr($key, 0, $methodBreaker);
            if (method_exists($model, $method)) {
                if (method_exists($model->$method, $submethod = str_replace($method.'.', '', $key))) {
                    return $model->$method->$submethod();
                }

                if (isset($model->$method->$submethod)) {
                    return $model->$method->$submethod;
                }

                return $model->getRelationValue($method);
            }
        }

        return false;
    }
520875
public static function gets($keys = null)
    {
        $noInitModel = static::buildNoInitModel();
        $query = static::find();
        if ($keys == null) {
            $models = $query->all();
        } elseif (is_array($keys)) {
            $array = [];
            foreach ($keys as $key) {
                if (is_string($key) && strlen($key)) {
                    $array[] = $key;
                }
            }
            $models = $query->where([$noInitModel->idAttribute => $array])->all();
        }
        $result = [];
        foreach ($models as $key => $model) {
            $result[$model->key] = $model->value;
        }
        return $result;
    }
691586
protected function getRelations($keys, $constraint = null)
	{
		if (isset($constraint))
		{
			call_user_func_array($constraint, array($this->related));
		}

		return $this->related
		            ->whereIn($this->relatedKey, array_unique($keys))
		            ->whereEquals($this->shifter, strtolower($this->model->getModelName()));
	}
104980
public function map(Builder $builder, $results, $model)
    {
        if (empty($results)) {
            return Collection::make();
        }

        $keys = $this->mapIds($results);

        $results = collect($results);

        $models = $model->whereIn($model->getKeyName(), $keys->all())
            ->get()
            ->keyBy($model->getKeyName());

        return $results->pluck($model->getKeyName())
            ->intersect($models->keys()) // Filter out no longer existing models (i.e. soft deleted)
            ->map(function ($key) use ($model, $models) {
                return $models[$key];
            });
    }
666773
public function map($results, $model)
    {
        if (count($results['ids']) === 0) {
            return Collection::make();
        }

        $keys = collect($results['ids'])->values()->all();
        $fieldsWheres = array_keys($this->builder->wheres);
        $models = $model->whereIn(
            $model->getQualifiedKeyName(),
            $keys
        )->get()->keyBy($model->getKeyName());

        return collect($results['ids'])->map(function ($hit) use ($models) {
            return $models->has($hit) ? $models[$hit] : null;
        })->filter(function ($model) use ($fieldsWheres) {
            return ! is_null($model) && array_reduce($fieldsWheres, function ($carry, $item) use ($model) {
                return $carry && $model[$item] == $this->builder->wheres[$item];
            }, true);
            ;
        });
    }
892650
public function matchRelation($model, $results) {
        $data = [];
        foreach ($results as $item) {
            if (!$this->isMatchRelation($model, $item)) {
                continue;
            }
            if ($this->type == self::TYPE_ONE) {
                return $item;
            }
            $data[] = $item;
        }
        return $data;
    }
686597
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, null);
        }

        return $models;
    }
582715
public function getRelationships($model): iterable
    {
        assert($model instanceof ModelInterface);

        foreach ($this->getRelationshipsMapping() as $jsonRelName => [$modelRelName, $belongsToFkName, $reverseType]) {
            // if model has relationship data then use it
            if ($this->hasProperty($model, $modelRelName) === true) {
                yield $jsonRelName => $this->createRelationshipRepresentationFromData(
                    $model,
                    $modelRelName,
                    $jsonRelName
                );
                continue;
            }

            // if relationship is `belongs-to` and has that ID we can add relationship as identifier
            if ($belongsToFkName !== null && $this->hasProperty($model, $belongsToFkName) === true) {
                $reverseIndex = $model->{$belongsToFkName};
                $identifier   = $reverseIndex === null ?
                    null : new Identifier((string)$reverseIndex, $reverseType, false, null);

                yield $jsonRelName => [
                    static::RELATIONSHIP_DATA       => $identifier,
                    static::RELATIONSHIP_LINKS_SELF => $this->isAddSelfLinkInRelationshipWithData($jsonRelName),
                ];
                continue;
            }

            // if we are here it's nothing left but show relationship as a link
            yield $jsonRelName => [static::RELATIONSHIP_LINKS_SELF => true];
        }
    }
185673
protected function getEagerModelKeys(array $models)
    {
        $keys = [];

        // First we need to gather all of the keys from the parent models so we know what
        // to query for via the eager loading query. We will add them to an array then
        // execute a "where in" statement to gather up all of those related records.
        foreach ($models as $model) {
            if (is_array($this->foreignKey)) { //Check for multi-columns relationship
                $keys[] = array_map(function ($k) use ($model) {
                    return $model->{$k};
                }, $this->foreignKey);
            } else {
                if (! is_null($value = $model->{$this->foreignKey})) {
                    $keys[] = $value;
                }
            }
        }

        // If there are no keys that were not null we will just return an array with either
        // null or 0 in (depending on if incrementing keys are in use) so the query wont
        // fail plus returns zero results, which should be what the developer expects.
        if (count($keys) === 0) {
            return [$this->relationHasIncrementingId() ? 0 : null];
        }

        sort($keys);

        return array_values(array_unique($keys, SORT_REGULAR));
    }