Creates a reference for storage of a related model in the database

@param   RelationshipMetadata    $relMeta
@param   Model                   $model
@return  mixed
513876
private function createReference(RelationshipMetadata $relMeta, Model $model)
    {
        $reference = [];
        $identifier = $this->getIdentifierDbValue($model->getId());
        if (true === $relMeta->isPolymorphic()) {
            $reference[Persister::IDENTIFIER_KEY]  = $identifier;
            $reference[Persister::POLYMORPHIC_KEY] = $model->getType();
            return $reference;
        }
        return $identifier;
    }
941489
public function createWith(array $model, array $related) {
        $cypher = $this->grammar->compileCreateWith($this, compact('model', 'related'));

        // Indicate that we need the result returned as is.
        $result = true;
        return $this->connection->statement($cypher, [], $result);
    }
298691
public function setManyToManyRelation($rel)
    {
        $key = $rel['refTable']->getModelName();
        $this->_m2mRelations[$key] = $rel;
        $this->getDocument()->addLog(sprintf('Applying N <=> N relation "%s" for "%s <=> %s"', $rel['refTable']->getParameters()->get('name'), $this->getModelName(), $key));

        return $this;
    }
797181
protected function reindexModel(Model $model)
    {
        $mapping = $this->option('mapping') ? json_decode(File::get($this->option('mapping')), true) : null;

        $this->info('---> Reindexing ' . get_class($model));

        $model->reindex(
            $this->option('relations'),
            $this->option('batch'),
            $mapping,
            function ($batch)
            {
                $this->info("* Batch ${batch}");
            }
        );
    }
744701
protected function getNestedRelation(Model $model, $relationArray)
    {
        $relation = null;
        foreach ($relationArray as $relation) {
            /** @var Relation $relation */
            $relation = $model->newQuery()->getRelation($relation);
            if ($relation) {
                $model = $relation->getRelated();
            }
        }

        return $relation;
    }
67385
private function _loadOrCreateRelationModel($data, $fks, $modelClass, $relationName)
    {

        /** @var BaseActiveRecord $relationModel */
        $relationModel = null;
        if (!empty($fks)) {
            $relationModel = $modelClass::findOne($fks);
        }
        if (!($relationModel instanceof BaseActiveRecord) && !empty($data)) {
            $relationModel = new $modelClass;
        }
        // If a custom scenario is set, apply it here to correctly be able to set the model attributes
        if (array_key_exists($relationName, $this->_relationsScenario)) {
            $relationModel->setScenario($this->_relationsScenario[$relationName]);
        }
        if (($relationModel instanceof BaseActiveRecord) && is_array($data)) {
            $relationModel->setAttributes($data);
            if ($relationModel->hasMethod('loadRelations')) {
                $relationModel->loadRelations($data);
            }

        }
        return $relationModel;
    }
797962
protected function getReferenceSource(Model $model, $source = null)
    {
        if (null === $source) {
            // Get model information for the model
            $information = $this->getInformationRepository()->getByModel($model);

            if ($information && $information->reference->source) {
                $source = $information->reference->source;
            }
        }

        if ( ! $source) return null;

        return $source;
    }
1051777
protected function setRelationships(Metadata\EntityMetadata $metadata, array $relMapping)
    {
        $allTypes = $this->getAllTypeNames();
        foreach ($relMapping as $key => $mapping) {
            if (!is_array($mapping)) {
                $mapping = ['type' => null, 'entity' => null];
            }

            if (!in_array($mapping['entity'], $allTypes)) {
                throw new RuntimeException(sprintf('No YAML mapping file was found for related entity type "%s" as found on relationship field "%s::%s"', $mapping['entity'], $metadata->type, $key));
            }

            $relationship = new Metadata\RelationshipMetadata($key, $mapping['type'], $mapping['entity']);
            $metadata->addRelationship($relationship);
        }
        return $metadata;
    }
60612
public function addRelationship(RelationshipMetadata $relationship)
    {
        if (isset($this->attributes[$relationship->getKey()])) {
            throw MetadataException::fieldKeyInUse('relationship', 'attribute', $relationship->getKey(), $this->type);
        }
        $this->relationships[$relationship->getKey()] = $relationship;
        ksort($this->relationships);
        return $this;
    }
643025
protected function determineModelReferenceStrategy(Model $model, $strategy = null)
    {
        if (null !== $strategy) {
            $strategy = $this->makeReferenceStrategyInstance($strategy);
        }

        if ( ! $strategy) {
            $strategy = $this->makeReferenceStrategy($model);
        }

        if ( ! $strategy) {
            $strategy = $this->getDefaultReferenceStrategyInstance();
        }

        return $strategy;
    }
159118
public function createEmbedCollection(EmbeddedPropMetadata $embededPropMeta, array $embedDocs = null)
    {
        if (empty($embedDocs)) {
            $embedDocs = [];
        }
        if (false === $this->isSequentialArray($embedDocs)) {
            throw StoreException::badRequest(sprintf('Improper has-many data detected for embed "%s" - a sequential array is required.', $embededPropMeta->getKey()));
        }

        $embeds = [];
        foreach ($embedDocs as $embedDoc) {
            $embeds[] = $this->loadEmbed($embededPropMeta->embedMeta, $embedDoc);
        }

        return new Collections\EmbedCollection($embededPropMeta->embedMeta, $this, $embeds);
    }
834260
public function relatedPatch(ApiRequest $request, $resourceModel)
    {
        $requestModel = $request->asRequestModel();

        $this->validate($requestModel, $this->getUpdatingRules());

        /** @var BelongsToMany $relation */
        $relation = $this->getRelation($resourceModel);

        $data = $requestModel->map(function (RequestModel $model) use ($relation) {
            $attributes = $this->getUpdatableAttributes($relation, $model);
            if (!empty($attributes)) {
                return [$model->id() => $attributes];
            }

            return $model->id();
        });

        $relation->sync($data->all());

        return $this->getRelation($resourceModel->fresh())->get();
    }
64296
public static function resolveRelation($model, $relModel)
    {
        if (is_string($relModel) &&
            BaseOrm::RECURSIVE_RELATIONSHIP_CONSTANT == $relModel) {
            return self::resolveRelation($model, $model);
        } elseif ($relModel instanceof Model) {
            return $relModel->getMeta()->getNSModelName();
        }

        return $relModel;
    }
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;
    }
1172768
public function link(Model $model) {
        $this->getRelation($this->getAlias(get_class($model)))->link($model);

        return $this;
    }
986868
protected function serializeRelationship(Model $owner, $relationship = null, RelationshipMetadata $relMeta, AdapterInterface $adapter)
    {
        if ($relMeta->isOne()) {
            if (is_array($relationship)) {
                throw SerializerException::badRequest('Invalid relationship value.');
            }
            $serialized = $this->serializeHasOne($owner, $relationship, $adapter);
        } elseif (is_array($relationship) || null === $relationship) {
            $serialized = $this->serializeHasMany($owner, $relationship, $adapter);
        } else {
            throw SerializerException::badRequest('Invalid relationship value.');
        }

        $ownerMeta = $owner->getMetadata();
        $serialized['links'] = [
            'self'      => $adapter->buildUrl($ownerMeta, $owner->getId(), $relMeta->getKey()),
            'related'   => $adapter->buildUrl($ownerMeta, $owner->getId(), $relMeta->getKey(), true),
        ];
        return $serialized;
    }
165402
public function relatedPatch(ApiRequest $request, $resourceModel)
    {
        $requestModel = $request->asRequestModel();

        $relationshipModel = $this->getRelationshipModel($resourceModel);

        $this->validate($requestModel, $this->getUpdatingRules());

        return $this->updateRelationshipModel($relationshipModel, $requestModel);
    }