Set the closure that will be used to populate the foreign key of a Morph To relation.

@param  array    $formatters
@param  MorphTo  $relation
@param  bool     $seeding
@return void
972223
protected function associateMorphTo(array &$formatters, MorphTo $relation, $seeding) {
        // Removes the table names from the foreign key and the morph type.
        $foreignKey = last(explode('.', $relation->{$this->getBelongsToForeignKeyNameMethod()}()));
        $morphType = last(explode('.', $relation->getMorphType()));

        $alwaysAssociate = $this->columns[$foreignKey]->getNotnull() || !$seeding;

        $formatters[$foreignKey] = function ($model, $insertedPKs) use ($alwaysAssociate) {
            if (!($morphOwner = $this->pickMorphOwner($insertedPKs, $alwaysAssociate))) {
                return null;
            }

            $randomElement = $this->generator->randomElement($insertedPKs[$morphOwner]);

            return $randomElement;
        };

        $formatters[$morphType] = function ($model, $insertedPKs) use ($alwaysAssociate) {
            if (!($morphOwner = $this->pickMorphOwner($insertedPKs, $alwaysAssociate))) {
                return null;
            }

            return (new $morphOwner)->getMorphClass();
        };
    }
888791
public function produceByRelation(Garp_Spawn_Relation $relation) {
        $this->setRelation($relation);

        if ($relation->type !== 'hasAndBelongsToMany') {
            throw new Exception(self::ERROR_GET_BINDING_MODEL_WRONG_RELATION_TYPE);
        }

        $bindingModelConfig = $this->_getBindingModelConfig();
        $model = new Garp_Spawn_Model_Binding($bindingModelConfig);

        return $model;
    }
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;
            }
        }
    }
796697
public function declareTables(SchemaBuilder $builder): array
    {
        $sourceContext = $this->definition->sourceContext();

        if (!interface_exists($target = $this->definition->getTarget())) {
            throw new RelationSchemaException("Morphed relations can only be pointed to an interface");
        }

        if (!$this->option(Record::CREATE_PIVOT)) {
            //No pivot table creation were requested, noting really to do
            return [];
        }

        $outerKey = $this->findOuter($builder);
        if (empty($outerKey)) {
            throw new RelationSchemaException("Unable to build morphed relation, no outer record found");
        }

        //Make sure all tables has same outer
        $this->verifyOuter($builder, $outerKey);

        $pivotTable = $builder->requestTable(
            $this->option(Record::PIVOT_TABLE),
            $sourceContext->getDatabase(),
            false,
            true
        );

        /*
         * Declare columns in map/pivot table.
         */
        $thoughtInnerKey = $pivotTable->column($this->option(Record::THOUGHT_INNER_KEY));
        $thoughtInnerKey->nullable(false);
        $thoughtInnerKey->setType($this->resolveType(
            $sourceContext->getColumn($this->option(Record::INNER_KEY))
        ));

        $thoughtOuterKey = $pivotTable->column($this->option(Record::THOUGHT_OUTER_KEY));
        $thoughtOuterKey->nullable(false);
        $thoughtOuterKey->setType($this->resolveType($outerKey));

        //Morph key
        $thoughtMorphKey = $pivotTable->column($this->option(Record::MORPH_KEY));
        $thoughtMorphKey->nullable(false);
        $thoughtMorphKey->string(static::MORPH_COLUMN_SIZE);

        /*
         * Declare user columns in pivot table.
         */
        $rendered = new ColumnRenderer();
        $rendered->renderColumns(
            $this->option(Record::PIVOT_COLUMNS),
            $this->option(Record::PIVOT_DEFAULTS),
            $pivotTable
        );

        //Map might only contain unique link between source and target
        if ($this->option(Record::CREATE_INDEXES)) {
            $pivotTable->index([
                $thoughtInnerKey->getName(),
                $thoughtOuterKey->getName(),
                $thoughtMorphKey->getName()
            ])->unique();
        }

        //There is only 1 constrain
        if ($this->isConstrained()) {
            $this->createForeign(
                $pivotTable,
                $thoughtInnerKey,
                $sourceContext->getColumn($this->option(Record::INNER_KEY)),
                $this->option(Record::CONSTRAINT_ACTION),
                $this->option(Record::CONSTRAINT_ACTION)
            );
        }

        return [$pivotTable];
    }
307336
private void populateRelations(EntityMetadata m, Object entity, Map<String, Object> relationMap, Node node,
            Map<Long, Object> nodeIdToEntityMap)
    {
        // Populate all relationship entities that are in Neo4J
        for (Relation relation : m.getRelations())
        {
            if (relation != null)
            {
                Class<?> targetEntityClass = relation.getTargetEntity();
                EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                        targetEntityClass);
                Field property = relation.getProperty();
                if (relation.getPropertyType().isAssignableFrom(Map.class))
                {
                    Map<Object, Object> targetEntitiesMap = new HashMap<Object, Object>();

                    // If relationship entity is stored into Neo4J, fetch it
                    // immediately
                    if (isEntityForNeo4J(targetEntityMetadata))
                    {

                        for (Relationship relationship : node.getRelationships(Direction.OUTGOING,
                                DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                        {
                            if (relationship == null)
                            {
                                continue;
                            }

                            // Target Entity
                            Node endNode = relationship.getEndNode();
                            if (endNode == null)
                            {
                                continue;
                            }
                            Object targetEntity = nodeIdToEntityMap.get(endNode.getId());
                            if (targetEntity == null)
                            {
                                targetEntity = mapper.getEntityFromNode(endNode, targetEntityMetadata);
                            }

                            // Relationship Entity
                            Object relationshipEntity = mapper.getEntityFromRelationship(relationship, m, relation);

                            // If this relationship is bidirectional, put source
                            // entity into Map field for target entity
                            Field bidirectionalField = relation.getBiDirectionalField();
                            Map<Object, Object> sourceEntitiesMap = new HashMap<Object, Object>();
                            if (bidirectionalField != null)
                            {
                                for (Relationship incomingRelationship : endNode.getRelationships(Direction.INCOMING,
                                        DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                                {
                                    Node startNode = incomingRelationship.getStartNode();
                                    Object sourceEntity = nodeIdToEntityMap.get(startNode.getId());
                                    if (sourceEntity == null)
                                    {
                                        sourceEntity = mapper.getEntityFromNode(startNode, m);
                                        nodeIdToEntityMap.put(startNode.getId(), sourceEntity);
                                    }
                                    sourceEntitiesMap.put(relationshipEntity, sourceEntity);
                                }
                                PropertyAccessorHelper.set(targetEntity, bidirectionalField, sourceEntitiesMap);
                            }

                            // Set references to Target and owning entity in
                            // relationship entity
                            Class<?> relationshipClass = relation.getMapKeyJoinClass();
                            for (Field f : relationshipClass.getDeclaredFields())
                            {
                                if (!ReflectUtils.isTransientOrStatic(f))
                                {

                                    if (f.getType().equals(m.getEntityClazz()))
                                    {
                                        PropertyAccessorHelper.set(relationshipEntity, f, entity);
                                    }
                                    else if (f.getType().equals(targetEntityClass))
                                    {
                                        PropertyAccessorHelper.set(relationshipEntity, f, targetEntity);
                                    }
                                }
                            }
                            targetEntitiesMap.put(relationshipEntity, targetEntity);
                        }

                        PropertyAccessorHelper.set(entity, property, targetEntitiesMap);
                    }

                    /**
                     * If relationship entity is stored in a database other than
                     * Neo4J foreign keys are stored in "Proxy Nodes", retrieve
                     * these foreign keys and set into EnhanceEntity
                     */
                    else
                    {

                        for (Relationship relationship : node.getRelationships(Direction.OUTGOING,
                                DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                        {
                            Node proxyNode = relationship.getEndNode();

                            String targetEntityIdColumnName = ((AbstractAttribute) targetEntityMetadata
                                    .getIdAttribute()).getJPAColumnName();
                            Object targetObjectId = proxyNode.getProperty(targetEntityIdColumnName);
                            Object relationshipEntity = mapper.getEntityFromRelationship(relationship, m, relation);

                            targetEntitiesMap.put(targetObjectId, relationshipEntity);
                        }

                        relationMap.put(relation.getJoinColumnName(kunderaMetadata), targetEntitiesMap);
                    }
                }
            }
        }
    }
395832
function ( relationships, deformerNodes ) {

			var rawMorphTargets = [];

			for ( var i = 0; i < relationships.children.length; i ++ ) {

				if ( i === 8 ) {

					console.warn( 'FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.' );

					break;

				}

				var child = relationships.children[ i ];

				var morphTargetNode = deformerNodes[ child.ID ];

				var rawMorphTarget = {

					name: morphTargetNode.attrName,
					initialWeight: morphTargetNode.DeformPercent,
					id: morphTargetNode.id,
					fullWeights: morphTargetNode.FullWeights.a

				};

				if ( morphTargetNode.attrType !== 'BlendShapeChannel' ) return;

				var targetRelationships = connections.get( parseInt( child.ID ) );

				targetRelationships.children.forEach( function ( child ) {

					if ( child.relationship === undefined ) rawMorphTarget.geoID = child.ID;

				} );

				rawMorphTargets.push( rawMorphTarget );

			}

			return rawMorphTargets;

		}
1271564
public function assignRelated($source, $relationNames=null, $meta=null)
    {
        if (!$source) { return; }

        $stack = [];
        $sourceIsArray = is_array($source) || $source instanceof \Traversable;
        if (!$sourceIsArray) {
            $source = array($source);
        }

        if ($meta !== null) {
            $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta;
        } else {
            $meta = $this->mapper->getMeta(get_class($source[0]));
        }

        if (!$relationNames) {
            if ($meta->autoRelations) {
                $relationNames = $meta->autoRelations;
            } else {
                throw new Exception("relationNames not passed, class {$meta->class} does not define autoRelations");
            }
        }

        $relationMap = [];
        foreach ((array)$relationNames as $relationName) {
            if (!isset($meta->relations[$relationName])) {
                throw new Exception("Unknown relation $relationName on {$meta->class}");
            }
            $relationMap[$relationName] = $rel = $meta->relations[$relationName];
            if ($rel['mode'] == 'class') {
                throw new Exception("Relation $relationName is not assignable for class {$meta->class}");
            }
        }

        $done = [];
        foreach ($relationMap as $relationName=>$relation) {
            if (isset($done[$relationName])) {
                continue;
            }
            $done[$relationName] = true;

            $missing = [];
            foreach ($source as $idx=>$item) {
                // we have to assume it's missing if we see a getter as there
                // may be serious unintended side effects from calling a getter
                // that may be unpopulated. it might lazy load if it's an active
                // record, or it might throw an exception because the 'set' hasn't
                // been called.

                // check for isset as well as falsey for the situation where we're using
                // stdClasses as the response object
                if (isset($relation['getter']) || !isset($item->{$relationName}) || !$item->{$relationName}) {
                    $missing[$idx] = $item;
                }
            }

            if ($missing) {
                $result = $this->getRelated($missing, $relationName, ['stack'=>$stack], $meta);
                $relator = $this->getRelator($meta, $relationName);
                $this->populateObjectsWithRelated($missing, $result, $relation);
            }
        }
    }
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;
    }
141017
protected static function handleMultiRelationCreate(Collection $multiValues, Relation $relation): void
    {
        $multiValues->each(function ($singleValues) use ($relation): void {
            self::handleSingleRelationCreate(new Collection($singleValues), $relation);
        });
    }
803917
public function declareTables(SchemaBuilder $builder): \Generator
    {
        foreach ($this->relations as $relation) {
            foreach ($relation->declareTables($builder) as $table) {
                yield $table;
            }
        }
    }
685103
protected function setPivotPopulator(BelongsToMany $relation)
    {
        $relatedClass = get_class($relation->getRelated());

        // If the many-to-many related model has not yet been added,
        // the pivot table will be populated along with it if it will be added.
        if (!$this->populator->wasAdded($relatedClass)) {
            return;
        }

        $this->pivotPopulators[$relatedClass] = new PivotPopulator(
            $this,
            $relation,
            $this->generator
        );
    }
1269386
protected function getGuessedColumnFormatters($model, $seeding, $populateForeignKeys = false)
    {
        $this->setColumns($model);

        $formatters = [];

        $nameGuesser = new Name($this->generator);
        $columnTypeGuesser = new ColumnTypeGuesser($this->generator);

        foreach ($this->columns as $columnName => $column) {
            // Skips autoincremented primary keys.
            if ($model instanceof Model && $columnName === $model->getKeyName() && $column->getAutoincrement()) {
                continue;
            }

            // And deleted_at.
            if (
                method_exists($model, 'getDeletedAtColumn')
                && $columnName === $model->getDeletedAtColumn()
            ) {
                continue;
            }

            if (
                !$seeding && $model instanceof Model &&
                ($columnName === $model->getCreatedAtColumn() || $columnName === $model->getUpdatedAtColumn())
            ) {
                continue;
            }

            // Guesses based on the column's name, and if unable to,
            // guesses based on the column's type.
            $formatter = $nameGuesser->guessFormat($columnName, $column->getLength())
                ?: $columnTypeGuesser->guessFormat($column, $model->getTable());

            if (!$formatter) {
                continue;
            }

            if ($column->getNotnull() || !$seeding) {
                $formatters[$columnName] = $formatter;
            } else {
                $formatters[$columnName] = function () use ($formatter) {
                    return rand(0, 1) ? $formatter() : null;
                };
            }
        }

        return $populateForeignKeys ? $this->populateForeignKeys($formatters, $seeding) : $formatters;
    }
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;
    }
995808
public function morphMany($related, $name, $type = null, $id = null, $localKey = null)
    {
        $instance = $this->newRelatedInstance($related);

        // Here we will gather up the morph type and ID for the relationship so that we
        // can properly query the intermediate table of a relation. Finally, we will
        // get the table and create the relationship instances for the developers.
        [$type, $id] = $this->getMorphs($name, $type, $id);

        $table = $instance->getTable();

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

        return $this->newMorphMany($instance->newQuery(), $this, $table.'.'.$type, $table.'.'.$id, $localKey);
    }
73030
protected function updateOrCreateHasMany(array $fillable, Model $model, Relation $relation)
    {
        $keys = [];
        $id = '';
        $records = [];

        foreach ($fillable as $fields) {
            if (is_array($fields)) {
                if (array_key_exists('id', $fields)) {
                    $id = $fields['id'];
                }

                if (array_except($fields, ['id'])) {
                    $record = $relation->updateOrCreate(['id' => $id], $fields);
                    array_push($keys, $record->id);
                    array_push($records, $record);
                }
            } else {
                if (array_except($fillable, ['id'])) {
                    $record = $relation->updateOrCreate(['id' => $id], $fillable);
                    array_push($keys, $record->id);
                    array_push($records, $record);
                }
            }
        }

        if ($keys && (property_exists($this, 'pruneHasMany') && $this->pruneHasMany !== false)) {
            $notIn = $relation->getRelated()->whereNotIn('id', $keys)->get();
            foreach ($notIn as $record) {
                $record->delete();
            }
        }

        return $records;
    }
1063101
protected function assignRelations($relations)
    {
        foreach ($relations as $relation) {
            if (!$relation instanceof RelationInterface) {
                throw new ModelException(sprintf('Relation must be an instance of RelationInterface, got "%s"', $this->getType($relation)));
            }

            foreach (array_keys($relation->keys()) as $field) {
                $this->assertField($field);
            }

            $this->relations[$relation->name()] = $relation;
        }
    }
160794
public function initRelation(array $models, $relation)
    {
        foreach ($models as $model) {
            $model->setRelation($relation, $this->getDefaultFor($model));
        }

        return $models;
    }