Define an inverse morph relationship.

@param Model  $parent
@param string $related
@param string $name
@param string $type
@param string $id
@param string $otherKey
@param string $relation

@return \Illuminate\Database\Eloquent\Relations\BelongsTo
509812
public static function build(Model $parent, $related, $name, $type = null, $id = null, $otherKey = null, $relation = null)
    {
        // If no relation name was given, we will use this debug backtrace to extract
        // the calling method's name and use that as the relationship name as most
        // of the time this will be what we desire to use for the relationships.
        if (is_null($relation)) {
            [$current, $caller] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);

            $relation = $caller['function'];
        }

        $morphName = array_get(array_flip(Relation::morphMap()), $related, $related);

        [$type, $id] = self::getMorphs(snake_case($name), $type, $id);

        $instance = new $related();

        // Once we have the foreign key names, we'll just create a new Eloquent query
        // for the related models and returns the relationship instance which will
        // actually be responsible for retrieving and hydrating every relations.
        $query = $instance->newQuery();

        $otherKey = $otherKey ?: $instance->getKeyName();

        return new self($query, $parent, $morphName, $type, $id, $otherKey, $relation);
    }
1221271
protected function addPolymorphicRelations(Model $model, $morphName, array $relatedTables)
    {
        foreach ($relatedTables as $relatedTable) {
            $relatedModel = $this->models[$relatedTable];

            if ($this->isOneToOneRelation($relatedModel, $model, $morphName)) {
                $relatedModel->morphOne($model, $morphName);
            } else {
                $relatedModel->morphMany($model, $morphName);
            }
        }

        $model->morphTo($morphName);
    }
1260230
public function inverseDefinition(SchemaBuilder $builder, $inverseTo): \Generator
    {
        if (!is_array($inverseTo) || count($inverseTo) != 2) {
            throw new DefinitionException(
                "BelongsToMorphed relation inverse must be defined as [type, outer relation name]"
            );
        }

        foreach ($this->findTargets($builder) as $schema) {
            /**
             * We are going to simply replace outer key with inner key and keep the rest of options intact.
             */
            $inversed = new RelationDefinition(
                $inverseTo[1],
                $inverseTo[0],
                $this->definition->sourceContext()->getClass(),
                [
                    Record::INNER_KEY         => $this->findOuter($builder)->getName(),
                    Record::OUTER_KEY         => $this->option(Record::INNER_KEY),
                    Record::CREATE_CONSTRAINT => false,
                    Record::CREATE_INDEXES    => $this->option(Record::CREATE_INDEXES),
                    Record::NULLABLE          => $this->option(Record::NULLABLE),
                    Record::MORPH_KEY         => $this->option(Record::MORPH_KEY)
                ]
            );

            //In back order :)
            yield $inversed->withContext(
                RelationContext::createContent(
                    $schema,
                    $builder->requestTable($schema->getTable(), $schema->getDatabase())
                ),
                $this->definition->sourceContext()
            );
        }
    }
1337819
public function foreignMany($related, $foreignKey = null, $localKey = null)
    {
        $instance = new $related;

        $foreignKey = $foreignKey ?: Str::snake(class_basename($this)).'_id';

        $localKey = $localKey ?: '_id';

        return new ForeignMany($this, $instance->query(['*']), $foreignKey, $localKey);
    }
1036793
protected function joinIntermediate(Model $parent, Relation $relation, $type)
    {
        if ($relation instanceof BelongsToMany) {
            $table = $relation->getTable();
            $fk = $relation->getQualifiedForeignPivotKeyName();
        } else {
            $table = $relation->getParent()->getTable();
            $fk = $relation->getQualifiedFirstKeyName();
        }

        $pk = $parent->getQualifiedKeyName();

        if (!$this->alreadyJoined($join = (new Join($this->query, $type, $table))->on($fk, '=', $pk))) {
            $this->query->joins[] = $join;
        }
    }
1048576
public function parentModel()
    {
        if ($this->value
            && ($relation = $this->guessRelation())
            && ($model = $this->getModel())
            && method_exists($model, $relation)) {
            return $model->$relation;
        }
    }
1156831
protected function belongsTo($referenceModel, $foreignKey = null)
    {
        return (new Relations\BelongsTo(
            new Relations\Maps\Inverse($this, $referenceModel, $foreignKey)
        ))->getResult();
    }
711479
public function morphMany(Model $relatedModel, $morphName)
    {
        if ($relatedModel->isIgnored()) {
            return;
        }

        $this->relations->add(
            new Relations\MorphMany($this, $relatedModel, $morphName)
        );
    }
115352
public function newRelatedInstanceFor(Model $parent)
    {
        $newInstance = $this->related->newInstance();

        if (is_array($this->localKey)) { //Check for multi-columns relationship
            $foreignKey = $this->getForeignKeyName();

            foreach ($this->localKey as $index => $key) {
                $newInstance->setAttribute($foreignKey[$index], $parent->{$key});
            }
        } else {
            return $newInstance->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey});
        }
    }
1139813
public function determineFormStoreStrategy(ModelRelationData $data)
    {
        $type       = null;
        $parameters = [];

        // Determine strategy alias
        switch ($data->type) {

            case RelationType::BELONGS_TO:
            case RelationType::BELONGS_TO_THROUGH:
            case RelationType::MORPH_ONE:
            case RelationType::HAS_ONE:
                $type = FormStoreStrategy::RELATION_SINGLE_KEY;
                break;

            case RelationType::BELONGS_TO_MANY:
            case RelationType::HAS_MANY:
            case RelationType::MORPH_MANY:
            case RelationType::MORPH_TO_MANY:
            case RelationType::MORPHED_BY_MANY:
                $type = FormStoreStrategy::RELATION_PLURAL_KEYS;
                break;

            case RelationType::MORPH_TO:
                $type = FormStoreStrategy::RELATION_SINGLE_MORPH;
                break;
        }


        // Determine parameters

        if ($data->translated) {
            $parameters[] = 'translated';
        }

        if (count($parameters)) {
            $type .= ':' . implode(',', $parameters);
        }

        return $type;
    }
636244
public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
    {
        $args = func_get_args();
        $args['type'] = 'belongsTo';
        return $this->setRelationship(json_encode($args));
    }
1203876
protected function morphEagerTo($name, $type, $id, $ownerKey)
    {
        return $this->newMorphTo(
            $this->newQuery()->setEagerLoads([]), $this, $id, $ownerKey, $type, $name
        );
    }
1007076
public static function newFromBuilderRecursive(Model $model, array $attributes = [], Relation $parentRelation = null)
    {
        $instance = $model->newInstance([], $exists = true);

        $instance->setRawAttributes((array)$attributes, $sync = true);

        // Load relations recursive
        static::loadRelationsAttributesRecursive($instance);
        // Load pivot
        static::loadPivotAttribute($instance, $parentRelation);

        return $instance;
    }
108396
public function embedsMany($parent, string $relatedClass, string $relation = null): EmbedsMany
    {
        if (is_null($relation)) {
            list(, $caller) = debug_backtrace(false);
            $relation = $caller['function'];
        }

        $this->addEmbeddedRelation($relation);
        $this->addNonProxyRelation($relation);

        return new EmbedsMany($parent, $relatedClass, $relation);
    }
38461
public function belongsToThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null)
    {
        $through = new $through;

        $firstKey = $firstKey ?: $this->getForeignKey();

        $secondKey = $secondKey ?: $through->getForeignKey();

        $localKey = $localKey ?: $this->getKeyName();

        return new BelongsToThrough((new $related)->newQuery(), $this, $through, $firstKey, $secondKey, $localKey);
    }
1366572
public function parentRelations(array $relations): ModelList
    {
        $this->main['parents'] = [];

        foreach ($relations as $key => $value) {

            if (is_string($key)) {
                $parent = [
                    'relation' => $key,
                    'field'    => $value,
                ];
            } else {
                $parent = [
                    'relation' => $value,
                    'field'    => $value,
                ];
            }

            $this->main['parents'][] = $parent;
        }

        return $this;
    }
676884
public function getByType( $parentId, $parentType, $type ) {

		$modelClass = static::$modelClass;

		return $modelClass::findByType( $parentId, $parentType, $type );
	}