Builds the relationship object based on user schema

@param  array        $relInfo relationship info from user schema
@return Relationship
439471
public function buildRelationship(array $relInfo)
    {
        $relationship = new Relationship($relInfo['start'], $relInfo['end'], $relInfo['type']);
        $relationship->setCardinality($relInfo['mode']);
        if (isset($relInfo['properties'])) {
            foreach ($relInfo['properties'] as $name => $info) {
                $property = $this->buildRelationshipProperty($name, $info);
                $relationship->addProperty($property);
            }
        }

        return $relationship;
    }
114731
public function reloadModelsWithRelationCount(): self
    {
        /** @var \Illuminate\Database\Eloquent\Builder $query */
        $query = $this->models()
            ->first()
            ->newQuery()
            ->withCount($this->relations);

        $ids = $this->getModelIds();

        $reloadedModels = $query
            ->whereKey($ids)
            ->get()
            ->filter(function (Model $model) use ($ids) {
                return in_array(
                    $model->getKey(),
                    $ids,
                    true
                );
            });

        return $this->setModels($reloadedModels);
    }
979719
public function loadAllRelsFor(Models $models, array $rels, $flags = null)
    {
        $rels = Arr::toAssoc($rels);

        foreach ($rels as $relName => $childRels) {
            $foreign = $this->loadRelFor($models, $relName, $flags);

            if ($childRels) {
                $rel = $this->getRel($relName);
                $rel->getRepo()->loadAllRelsFor($foreign, $childRels, $flags);
            }
        }

        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;
    }
850685
public function morphToMany($related, $name, $table = null, $foreignKey = null, $relatedKey = null, $inverse = false)
    {
        $caller = $this->guessBelongsToManyRelation();

        // First, we will need to determine the foreign key and "other key" for the
        // relationship. Once we have determined the keys we will make the query
        // instances, as well as the relationship instances we need for these.
        $instance = $this->newRelatedInstance($related);

        $foreignKey = $foreignKey ?: $name . '_id';

        $relatedKey = $relatedKey ?: $instance->getForeignKey();

        // Now we're ready to create a new query builder for this related model and
        // the relationship instances for this relation. This relations will set
        // appropriate query constraints then entirely manages the hydrations.
        $table = $table ?: Str::plural($name);

        return new MorphToMany(
            $instance->newQuery(),
            $this,
            $name,
            $table,
            $foreignKey,
            $relatedKey,
            $caller,
            $inverse
        );
    }
420470
public function rel($key) {
		$rt = $this->fieldConf[$key]['relType'];
		$rc = $this->fieldConf[$key][$rt];
		if (!is_array($rc))
			$rc = array($rc,'_id');
		return $this->getRelInstance($rc[0],null,$key);
	}
1095229
public function addRelationship(Relationship $relationship)
    {
        foreach ($this->relationships as $rel) {
            if ($rel->getType() === $relationship->getType() &&
            $rel->getStartNode() === $relationship->getStartNode() &&
            $rel->getEndNode() === $relationship->getEndNode()) {
                throw new SchemaDefinitionException(sprintf('There is already a relationship declared with TYPE "%s" and STARTNODE "%s" and ENDNODE "%s"',
                    $relationship->getType(), $relationship->getStartNode(), $relationship->getEndNode()));
            }
        }

        return $this->relationships->add($relationship);
    }
1123527
public function createRelationship($source, DocumentHydrator $hydrator): AbstractRelationship
    {
        if (! isset($source->data)) {
            return $this->processNoDataRelationship($source, $hydrator);
        }

        if (is_object($source->data)) {
            return $this->processSingleIdentifierRelationship($source, $hydrator);
        }

        if (is_array($source->data)) {
            return $this->processIdentifierCollectionRelationship($source, $hydrator);
        }

        throw new InvalidDocumentException('If data is present and is not null it must be an object or an array');
    }
1192751
protected function getForeignKeysArray($val, $rel_field, $key) {
		if (is_null($val))
			return NULL;
		if (is_object($val) && $val instanceof CortexCollection)
			$val = $val->getAll($rel_field,true);
		elseif (is_string($val))
			// split-able string of collection IDs
			$val = \Base::instance()->split($val);
		elseif (!is_array($val) && !(is_object($val)
				&& ($val instanceof Cortex && !$val->dry())))
			trigger_error(sprintf(self::E_MM_REL_VALUE, $key),E_USER_ERROR);
		// hydrated mapper as collection
		if (is_object($val)) {
			$nval = array();
			while (!$val->dry()) {
				$nval[] = $val->get($rel_field,true);
				$val->next();
			}
			$val = $nval;
		}
		elseif (is_array($val)) {
			// array of single hydrated mappers, raw ID value or mixed
			$isMongo = ($this->dbsType == 'mongo');
			foreach ($val as &$item) {
				if (is_object($item) &&
					!($isMongo && (($this->db->legacy() && $item instanceof \MongoId) ||
						(!$this->db->legacy() && $item instanceof \MongoDB\BSON\ObjectId)))) {
					if (!$item instanceof Cortex || $item->dry())
						trigger_error(self::E_INVALID_RELATION_OBJECT,E_USER_ERROR);
					else $item = $item->get($rel_field,true);
				}
				if ($isMongo && $rel_field == '_id' && is_string($item))
					$item = $this->db->legacy() ? new \MongoId($item) : new \MongoDB\BSON\ObjectId($item);
				if (is_numeric($item))
					$item = (int) $item;
				unset($item);
			}
		}
		return $val;
	}
1018588
private function getQueryRelConverter(Store $store, RelationshipMetadata $relMeta)
    {
        $related = $store->getMetadataForType($relMeta->getEntityType());
        return $this->getQueryRootConverter($related, Persister::IDENTIFIER_KEY);
    }
418582
public static function addJoin($query, $parentAlias, $schema, $relName, $nested=array(), $joinType='inner')
    {
        if (!in_array($joinType, array('inner','left','right'))) {
            throw new \InvalidArgumentException("Unsupported join type: $joinType");
        }

        list($relName, $alias) = self::parseRelName($relName);
        $rel = $schema->relationship($relName);

        // look up schema and table for both sides of join
        $instance = \Pheasant::instance();
        $localTable = $instance->mapperFor($schema->className())->table();
        $remoteSchema = $instance->schema($rel->class);
        $remoteTable = $instance->mapperFor($rel->class)->table();

        $joinMethod = $joinType.'Join';
        $query->$joinMethod($remoteTable->name()->table, sprintf(
            'ON `%s`.`%s`=`%s`.`%s`',
            $parentAlias,
            $rel->local,
            $alias,
            $rel->foreign
            ),
            $alias
        );

        foreach (self::normalizeMap($nested) as $relName=>$nested) {
            self::addJoin($query, $alias, $remoteSchema, $relName, $nested, $joinType);
        }
    }
505841
public function buildRelationshipsMetadata(\SimpleXMLElement $node, $className, \ReflectionClass $reflection)
    {
        $relationships = [];
        foreach ($node->relationship as $relationshipNode) {
            $relationships[] = $this->buildRelationshipMetadata($relationshipNode, $className, $reflection);
        }

        return $relationships;
    }
593365
private function buildRelationshipGetters() {
        $buffer = '';
        foreach($this->getRelationships() as $relationship) {
            $field = $this->getField($relationship->getLocalColumn());
            if($relationship->isPlural()) {
                $method = new Object\Method();
                $method->setAccess('public');
                $method->setDescription('Gets the related ' . $relationship->getAlias());
                $method->setName('get' . ucfirst($relationship->getAlias()));
                $method->setReturnType('ResultSet|Child' . $relationship->getRemoteShortModel() . '[]');
                $parameter = new Object\Parameter();
                $parameter->setDescription('');
                $parameter->setName('parameters');
                $parameter->setDefaultValue('null');
                $parameter->setType('array');
                $method->addParameter($parameter);
                $method->setContent('return $this->getRelated(\'' . $relationship->getAlias() . '\', $parameters);');
                $this->getAbstractClass()->addMethod($method);

                $method = new Object\Method();
                $method->setAccess('public');
                $method->setDescription('Gets the count of related ' . $relationship->getAlias());
                $method->setName('count' . ucfirst($relationship->getAlias()));
                $method->setReturnType('int');
                $parameter = new Object\Parameter();
                $parameter->setDescription('');
                $parameter->setName('parameters');
                $parameter->setDefaultValue('null');
                $parameter->setType('array');
                $method->addParameter($parameter);
                $method->setContent('return $this->get' . ucfirst($relationship->getAlias()) . '($parameters)->count();');
                $this->getAbstractClass()->addMethod($method);
            } else {

                $method = new Object\Method();
                $method->setAccess('public');
                $method->setDescription('Gets the related ' . $relationship->getAlias());
                $method->setName('get' . ucfirst($relationship->getAlias()));
                if($this->getAbstractClass()->hasMethod($method->getName())) {
                    $method->setName('getRelated' . ucfirst($relationship->getAlias()));
                }
                $method->setReturnType('Child' . $relationship->getRemoteShortModel() . '|false');
                $method->setContent('return $this->getRelated(\'' . $relationship->getAlias() . '\');');
                $this->getAbstractClass()->addMethod($method);

                if($field->isNullable()) {
                    $method = new Object\Method();
                    $method->setAccess('public');
                    $method->setDescription('Checks if a relationship exists');
                    $method->setName('has' . ucfirst($relationship->getAlias()));
                    $method->setReturnType('bool');
                    $method->setContent('return !is_null($this->get' . ucfirst($relationship->getAlias()) . '());');
                    $this->getAbstractClass()->addMethod($method);
                }
            }
        }
        return $buffer;
    }
1285819
public static function buildRelationQuery($entity, Relation $relation) {
        $relQuery = "";
        $getid = "getId";
        if ($relation->getCardinality() == Relation::$manyToMany) {
            $m = "get" . $relation->getName();
            $relQuery .= "INSERT INTO " . $relation->getTable() . " (" . $relation->getLocalColumn() . ", " . $relation->getForeignColumn() . ") ";
            $relQuery .= "VALUES (:" . $relation->getLocalColumn() . ", :" . $relation->getForeignColumn() . ");";
        }
        if ($relation->getCardinality() == Relation::$oneToMany) {
            $relMapper = MapperBuilder::buildFromName($this->mapping, $relation->getEntity());
            $m = "get" . $relation->getName();
            foreach ($entity->$m() as $rel) {
                $setid = "set" . $relMapper->getNameForColumn($relation->getForeignColumn());
                $rel->$setid($entity->$getid());
                $relQuery .= $this->buildInsertQuery($rel);
            }
        }


        return $relQuery;
    }
291184
public static function addRelationship($query, $relationship)
    {
        $property = $query->getRepository()->getDescription()->getProperty($relationship);

        switch (true) {
            case $property->isManyToOne() :
                return self::_parseManyToOne($query, $property);
            case $property->isManyToMany() :
                return self::_parseManyToMany($query, $property);
            case $property->isOneToMany() :
                return self::_parseOneToMany($query, $property);

        }
    }
322447
private static function buildRelationships(array $data): MapInterface
    {
        $relationships = new Map('int', Relationship::class);

        foreach ($data as $response) {
            foreach ($response['graph']['relationships'] as $rel) {
                $relationships = $relationships->put(
                    (int) $rel['id'],
                    new Relationship\Relationship(
                        new Id((int) $rel['id']),
                        new Type($rel['type']),
                        new Id((int) $rel['startNode']),
                        new Id((int) $rel['endNode']),
                        self::buildProperties($rel['properties'])
                    )
                );
            }
        }

        return $relationships;
    }
671819
function setRelatedTo( $relid, $params=FALSE ) {
    $relation           = array();
    if(( '<' == substr( $relid, 0, 1 )) &&
       ( '>' == substr( $relid, -1 )))
                 $relid = substr( $relid, 1, ( strlen( $relid ) - 2 ));
    $relation['value']  = $relid;
    $relation['params'] = $this->_setParams( $params );
            // remove default
    if( isset( $relation['params']['RELTYPE'] ) &&
       ( strtoupper( $relation['params']['RELTYPE'] ) == 'PARENT' ))
      unset( $relation['params']['RELTYPE'] );
    $this->relatedto[]  = $relation;
  }