Create Pivot Records.

@param \Analogue\ORM\Entity[] $relatedEntities

@return void
491767
public function createPivots($relatedEntities)
    {
        $keys = [];
        $attributes = [];

        $keyName = $this->relatedMap->getKeyName();

        foreach ($relatedEntities as $entity) {
            $keys[] = $entity->getEntityAttribute($keyName);
        }

        $records = $this->createAttachRecords($keys, $attributes);

        $this->query->getQuery()->from($this->table)->insert($records);
    }
52732
protected function loadRelatedEntities($entities, $depth)
    {
        if (0 <= $depth) {
            return;
        }
        $relatedEntities = [];
        foreach ($entities as $entity) {
            if (null === $entity) {
                continue;
            }
            $family = $entity->getFamily();
            foreach ($family->getAttributes() as $attribute) {
                $this->appendRelatedEntities($relatedEntities, $attribute, $entity);
            }
        }

        $this->load($relatedEntities, $depth - 1);
    }
4262
protected function hydratePivotRelation(array $models)
	{
		// To hydrate the pivot relationship, we will just gather the pivot attributes
		// and create a new Pivot model, which is basically a dynamic model that we
		// will set the attributes, table, and connections on so it they be used.
		foreach ($models as $model)
		{
			$pivot = $this->newExistingPivot($this->cleanPivotAttributes($model));

			$model->setRelation('pivot', $pivot);
		}
	}
1236587
public function loadRelations($data)
    {
        /** @var BaseActiveRecord $owner */
        $owner = $this->owner;
        foreach ($this->_relations as $relationName) {
            $keyName = $this->_getRelationKeyName($relationName);
            if (array_key_exists($keyName, $data)) {
                $owner->{$relationName} = $data[$keyName];
            }
        }
    }
678476
public function setEntities(array $entities)
    {
        foreach ($entities as $entity) {
            if (! $entity instanceof AbstractEntity) {
                $message = sprintf(
                    'Expected an array of entities. Array contains element of type %s.',
                    gettype($entity)
                );

                throw new InvalidArgumentException($message);
            }
        }

        $this->entities = $entities;
    }
92481
protected function postStoreProcess()
    {
        $aggregate = $this->aggregate;

        // Create any related object that doesn't exist in the database.
        $foreignRelationships = $aggregate->getEntityMap()->getForeignRelationships();

        $this->createRelatedEntities($foreignRelationships);

        // Update any pivot tables that has been modified.
        $aggregate->updatePivotRecords();

        // Update any dirty relationship. This include relationships that already exists, have
        // dirty attributes / newly created related entities / dirty related entities.
        $dirtyRelatedAggregates = $aggregate->getDirtyRelationships();

        foreach ($dirtyRelatedAggregates as $related) {
            $this->createStoreCommand($related)->execute();
        }

        // Now we can sync the related collections
        //
        // TODO (note) : not sure this check is needed, as we can assume
        // the aggregate exists in the Post Store Process
        if ($this->aggregate->exists()) {
            $this->aggregate->syncRelationships($foreignRelationships);
        }

        // TODO be move it to the wrapper class
        // so it's the same code for the entity builder
        $aggregate->setProxies();

        // Update Entity Cache
        $aggregate->getMapper()->getEntityCache()->refresh($aggregate);
    }
1043548
public function setTables($entityTables, $manyToManyTables)
    {
        $this->tables = $this->manyToManyTables = $this->classToTableNames = [];

        foreach ($entityTables as $table) {
            $className = $this->getClassNameForTable($table->getName());

            $this->classToTableNames[$className] = $table->getName();
            $this->tables[$table->getName()]     = $table;
        }

        foreach ($manyToManyTables as $table) {
            $this->manyToManyTables[$table->getName()] = $table;
        }
    }
317437
public function mapEntities(array $entityDefinitions)
	{
		foreach($entityDefinitions as $entityIdentifier => $entityDefinition)
		{
			$this->validateAndCompleteEntity($entityIdentifier, $entityDefinition);
		}
	}
313471
private function extractAssociatedEntities(array $entities)
    {
        $linkIds = $associatedEntities = [];

        foreach ($entities as $entity) {
            $reflect = new \ReflectionClass($entity);

            //If Widget is already in cache, extract only its Criterias (used outside Widget rendering)
            $widgetCached = ($entity instanceof Widget && $this->widgetHelper->isCacheEnabled($entity));

            //If Widget has LinkTrait, store the entity link id
            if (!$widgetCached && $this->hasLinkTrait($reflect) && $entity->getLink()) {
                $linkIds[] = $entity->getLink()->getId();
            }

            //Pass through all entity associations
            $metaData = $this->em->getClassMetadata(get_class($entity));
            foreach ($metaData->getAssociationMappings() as $association) {
                $targetClass = $association['targetEntity'];

                //Skip already set WidgetMap association
                if ($targetClass == WidgetMap::class) {
                    continue;
                }

                //If Widget has OneToOne or ManyToOne association, store target entity id to construct
                //a single query for this entity type
                if ($metaData->isSingleValuedAssociation($association['fieldName'])
                    && !$widgetCached
                ) {
                    //If target Entity is not null, treat it
                    if ($targetEntity = $this->accessor->getValue($entity, $association['fieldName'])) {
                        $associatedEntities[$targetClass]['id']['unsorted']['entitiesToWarm'][] = new AssociatedEntityToWarm(
                            AssociatedEntityToWarm::TYPE_MANY_TO_ONE,
                            $entity,
                            $association['fieldName'],
                            $targetEntity->getId()
                        );
                    }
                }

                //If Widget has OneToMany association, store owner entity id and mappedBy value
                //to construct a single query for this entity type
                elseif ($metaData->isCollectionValuedAssociation($association['fieldName'])) {

                    //Even if Widget is cached, we need its Criterias used before cache call
                    if (!$widgetCached || $targetClass === Criteria::class) {

                        //If Collection is not null, treat it
                        if ($this->accessor->getValue($entity, $association['fieldName'])) {

                            //Don't use Collection getter directly and override Collection
                            //default behaviour to avoid useless query
                            $getter = 'get'.ucwords($association['fieldName']);
                            $entity->$getter()->setDirty(false);
                            $entity->$getter()->setInitialized(true);
                            $orderByToken = 'unsorted';

                            if (isset($association['orderBy'])) {
                                $orderByToken = implode($association['orderBy']);
                                $associatedEntities[$targetClass][$association['mappedBy']][$orderByToken]['orderBy'] = $association['orderBy'];
                            }

                            $associatedEntities[$targetClass][$association['mappedBy']][$orderByToken]['entitiesToWarm'][] = new AssociatedEntityToWarm(
                                AssociatedEntityToWarm::TYPE_ONE_TO_MANY,
                                $entity,
                                $association['fieldName'],
                                $entity->getId()
                            );
                        }
                    }
                }
            }
        }

        $newEntities = $this->setAssociatedEntities($associatedEntities);
        $this->setPagesForLinks($linkIds);

        //Recursive call if previous has return new entities to warm
        if ($newEntities) {
            $this->extractAssociatedEntities($newEntities);
        }
    }
754301
protected function hasOneOrManyDeepForeignKeys(Model $related, array $throughParents, array $foreignKeys)
    {
        foreach (array_merge([$this], $throughParents) as $i => $instance) {
            /** @var \Illuminate\Database\Eloquent\Model $instance */
            if (! isset($foreignKeys[$i])) {
                if ($instance instanceof Pivot) {
                    $foreignKeys[$i] = ($throughParents[$i] ?? $related)->getKeyName();
                } else {
                    $foreignKeys[$i] = $instance->getForeignKey();
                }
            }
        }

        return $foreignKeys;
    }
1173225
public function create($related)
	{
		if($related instanceof $this->model)
		{
			$related->{$this->polymorphicType} = $this->parent->getClass();
		}
		else
		{
			$related[$this->polymorphicType] = $this->parent->getClass();
		}

		return parent::create($related);
	}
1085229
public function create($related)
	{
		if($related instanceof $this->model)
		{
			$related->{$this->getForeignKey()} = $this->parent->getPrimaryKeyValue();

			$related->save();

			return $related;
		}

		return $this->model->create([$this->getForeignKey() => $this->parent->getPrimaryKeyValue()] + $related);
	}
40336
public function insertRelationship($parent, $related, $relationship, $bindings = []) {
        $cypher = $this->grammar->compileEdge($this, $parent, $related, $relationship, $bindings);
        return $this->connection->insert($cypher, $bindings);
    }
478216
public function build(Entity $entity): void
    {
        $attributes = $entity->getEntityAttributes();

        // We will manually add a relationship for every attribute registered
        // of this entity. Once we know the relation method we have to use,
        // we will just add it to the entityAttributeRelations property.
        foreach ($attributes as $attribute) {
            $relation = $this->getRelationClosure($entity, $attribute);

            $entity->setEntityAttributeRelation($attribute->getAttribute('slug'), $relation);
        }
    }
156809
protected function initInstances(): MultipleRelation
    {
        if (is_array($this->data) && !empty($this->data)) {
            //Iterates and instantiate records
            $iterator = new RecordIterator($this->data, $this->class, $this->orm);

            foreach ($iterator as $pivotData => $item) {
                if (in_array($item, $this->instances, true)) {
                    //Skip duplicates (if any?)
                    continue;
                }

                $this->pivotData->attach($item, $pivotData);
                $this->instances[] = $item;
            }
        }

        //Memory free
        $this->data = [];

        return $this;
    }
276412
public function findLastForRelatedEntity($relatedEntity)
    {
        [$relClass, $relId] = $this->getRelatedEntityIdentifier($relatedEntity);

        $rsm = new ResultSetMappingBuilder($this->_em);
        $rsm->addRootEntityFromClassMetadata('JMSJobQueueBundle:Job', 'j');

        return $this->_em->createNativeQuery('SELECT j.* FROM jms_jobs j INNER JOIN jms_job_related_entities r ON r.job_id = j.id WHERE r.related_class = :relClass AND r.related_id = :relId', $rsm)
            ->setParameter('relClass', $relClass)
            ->setParameter('relId', $relId)
            ->getResult();
    }
882992
private function setPostedRelations(Entity\Content $content, $formValues)
    {
        /** @var Collection\Relations $related */
        $related = $this->em->createCollection(Entity\Relations::class);
        $related->setFromPost($formValues, $content);
        $content->setRelation($related);
    }