Create related object. One RIF-CS can have more than one related object nodes,
each object is described by one node.
\param $key
Type: string. The identifier of the related object.
\param $relation_type
Type: string. Type of relationship.
963689
protected function create_relatedObject($key, $relation_type)
    {
        $c = $this->addChild($this->working_node, 'relatedObject');
        $this->addChild($c, 'key', $key);
        $c = $this->addChild($c, 'relation');
        // Mimick ANDS with enpty value to get both tags for relation. Only for better display
        // $c = $this->addChild($c, 'relation','     ');
        $c->setAttribute('type', $relation_type);
    }
874308
public function addLink( $uri, $relation, $type = NULL ){
		$this->links[]	= array(
			'uri'		=> $uri,
			'rel'		=> $relation,
			'type'		=> $type
		);
	}
1221437
def _make_key(relation):
    
    return _ReferenceKey(_lower(relation.database),
                         _lower(relation.schema),
                         _lower(relation.identifier))
236150
public function hasMany(string $related, string $primary_key = '', string $foreign_key = '')
    {
        $relatedModel = app()->make($related);
        $local_key = $local_key ?? $this->getKey();
        // Make the table name singular and append ID to it
        // FIXME: Use a more reliable approach
        $foreign_key = $foreign_key ?? rtrim($relatedModel->getTable(), 's').'_id';
        return new HasMany($relatedModel, $this, $primary_key, $foreign_key);
    }
191935
function create(dataID: DataID, typeName: string): Record {
  // See perf note above for why we aren't using computed property access.
  const record = {};
  record[ID_KEY] = dataID;
  record[TYPENAME_KEY] = typeName;
  return record;
}
511262
protected function createChild($key)
    {
        $relation = $this->getValueOrRelationForKey($key);
        // if this is not a relation, then it's the actual value
        // returned by a method (like for example computed attributes)
        // so we just return it as the value

        if (!$relation instanceof Relation) {
            return $relation;
        }

        $this->supportedRelationOrThrow($key, $relation);

        // TODO we need to bind the relation to the datasource here
        $model = Rel::make($relation)->getChild();

        if (!$this->isEloquentObject($model)) {
            throw new \LogicException(sprintf(
                'newModelFromRelation should return an Eloquent Model/Collection, but returned a %s (parent: %s, key: %s, relation: %s)',
                get_type_class($model),
                get_type_class($this->getDelegatedStorage()), $key, get_type_class($relation)
            ));
        }

        return $model;
    }
433967
def create_relation(self, event, content_object, distinction=''):
        
        return EventRelation.objects.create(
            event=event,
            distinction=distinction,
            content_object=content_object)
43692
public GrRelation createRelation(String type, GrNode startNode, GrNode endNode) {
		return this.resultHandler.getLocalElements().createRelation(type, startNode, endNode);
	}
1018459
public function addProcessedRelation($key, $value, $type = RelationTypes::PRODUCT_RELATION)
    {

        // query whether or not the child SKU has already been processed
        if (isset($this->processedRelations[$type][$key])) {
            $this->processedRelations[$type][$key][] = $value;
        } else {
            $this->processedRelations[$type][$key] = array($value);
        }
    }
691238
private function joinMetaTable(Builder $q, string $key, $type = 'left')
    {
        $relation = $this->meta();
        $metaTable = $relation->getRelated()->getTable();

        // Create an alias for the join, to allow the same
        // table to be joined multiple times for different keys.
        $alias = $metaTable.'__'.$key;

        // If no explicit select columns are specified,
        // avoid column collision by excluding meta table from select.
        if (!$q->getQuery()->columns) {
            $q->select($this->getTable().'.*');
        }

        // Join the meta table to the query
        $q->join("{$metaTable} as {$alias}", function (JoinClause $q) use ($relation, $key, $alias) {
            // Laravel 5.4 changed the method names here
            $foreign_key = method_exists($relation, 'getForeignKeyName') ? $relation->getForeignKeyName() : $relation->getPlainForeignKey();
            $type = method_exists($relation, 'getForeignKeyName') ? $relation->getMorphType() : $relation->getPlainMorphType();

            $q->on($relation->getQualifiedParentKeyName(), '=', $alias.'.'.$foreign_key)
                ->where($alias.'.key', '=', $key)
                ->where($alias.'.'.$type, '=', get_class($this));
        }, null, null, $type);

        // Return the alias so that the calling context can
        // reference the table.
        return $alias;
    }
315416
def relation_types():
    """"""
    rel_types = []
    md = metadata()
    for key in ('provides', 'requires', 'peers'):
        section = md.get(key)
        if section:
            rel_types.extend(section.keys())
    return rel_types
666491
def create_by_natural_key(self, *args):
        

        kwargs = self.natural_key_kwargs(*args)
        for name, rel_to in self.model.get_natural_key_info():
            if not rel_to:
                continue
            nested_key = extract_nested_key(kwargs, rel_to, name)
            # Automatically create any related objects as needed
            if nested_key:
                kwargs[name], is_new = (
                    rel_to.objects.get_or_create_by_natural_key(*nested_key)
                )
            else:
                kwargs[name] = None
        return self.create(**kwargs)
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);
    }
94324
public function belongsTo($related, $foreignKey = 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)) {
            list($current, $caller) = debug_backtrace(false, 2);

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

        $specialType = $this->getCmsSpecialRelationType($relation);

        // If no foreign key was supplied, we can use a backtrace to guess the proper
        // foreign key name by using the name of the relationship function, which
        // when combined with an "_id" should conventionally match the columns.
        if (is_null($foreignKey)) {
            if ($specialType === self::RELATION_TYPE_CATEGORY) {
                $foreignKey = config('pxlcms.relations.categories.keys.category');
            } else {
                $foreignKey = Str::snake($relation);
            }
        }

        // If the relation name is the same (casing aside) as the foreign key attribute,
        // we must make sure that the foreign key property is at least a key in the
        // attributes array. If it is not, there will be recursive lookup problems
        // where the attribute is never resolved and 'property does not exist' exceptions occur.
        if (    snake_case($relation) == $foreignKey
            &&  ! array_key_exists($foreignKey, $this->attributes)
        ) {
            $this->attributes[ $foreignKey ] = null;
        }

        /** @var Builder $belongsTo */
        $belongsTo = parent::belongsTo($related, $foreignKey, $otherKey, $relation);

        // category relation must be filtered by module id
        if ($specialType === self::RELATION_TYPE_CATEGORY) {
            $belongsTo->where(
                config('pxlcms.relations.categories.keys.module'),
                $this->getModuleNumber()
            );
        }

        return $belongsTo;
    }
469232
protected function makeModelFormFieldDataForRelationData(ModelRelationData $relation, $key = null)
    {
        $required = (   in_array($relation->type, [
                            RelationType::BELONGS_TO,
                            RelationType::BELONGS_TO_THROUGH,
                            RelationType::MORPH_TO,
                        ])
                    &&  ! $relation->nullable_key);

        // Shows any relation, regardless of type. Note that this is not optimal for
        // records with a large number of to-many related items, for instance.

        return new ModelFormFieldData([
            'key'              => $key ?: $relation->name,
            'source'           => $relation->method,
            'required'         => $required,
            'translated'       => $relation->translated,
            'display_strategy' => $this->determineFormDisplayStrategyForRelation($relation),
            'store_strategy'   => $this->determineFormStoreStrategyForRelation($relation),
            'options'          => $this->determineFormStoreOptionsForRelation($relation),
        ]);
    }
227223
def _gather_keys_by_type(self, type):
        
        foreign = self._foreign_key

        keys = (
            BaseCollection.make(list(self._dictionary[type].values()))
            .map(lambda models: getattr(models[0], foreign))
            .unique()
        )

        return keys
633938
function parseRelations (data, relations, options) {
  var relationships = {}

  _.each(relations, function (relation, name) {
    var fkName = relation.keyTo

    // If relation is belongsTo then fk is the other way around
    if (utils.relationFkOnModelFrom(relation)) {
      fkName = relation.keyFrom
    }

    var pk = data[options.primaryKeyField]
    var fk = data[fkName]

    var toType = ''
    if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) {
      var discriminator = relation.polymorphic.discriminator
      var model = options.app.models[data[discriminator]]
      toType = utils.pluralForModel(model)
    } else {
      toType = utils.pluralForModel(relation.modelTo)
    }

    // Relationship `links` should always be defined unless this is a
    // relationship request
    if (!options.isRelationshipRequest) {
      relationships[name] = {
        links: {
          related: options.host +
            options.restApiRoot +
            '/' +
            options.modelPath +
            '/' +
            pk +
            '/' +
            name
        }
      }
    }

    var relationship = null

    if (!_.isUndefined(fk) && relation.modelTo !== relation.modelFrom) {
      if (_.isArray(fk)) {
        relationship = makeRelations(toType, fk, options)
      } else {
        relationship = makeRelation(toType, fk, options)
      }
    }

    // No `data` key should be present unless there is actual relationship data.
    if (relationship) {
      relationships[name].data = relationship
    } else if (relation.type === 'belongsTo') {
      relationships[name].data = null
    }
  })

  return relationships
}