Embed resources for the given relation
@param relation Embedded resource relation
@param resources Resources to embed
@return HAL resource
10946
public HalResource addEmbedded(String relation, HalResource... resources) {
    return addResources(HalResourceType.EMBEDDED, relation, true, resources);
  }
1353235
public static List<Link> getAllLinksForRelation(HalResource hal, String relation) {

    List<Link> links = Lists.newArrayList(hal.getLinks(relation));
    List<Link> embeddedLinks = hal.getEmbedded().values().stream()
        .flatMap(embedded -> getAllLinksForRelation(embedded, relation).stream())
        .collect(Collectors.toList());
    links.addAll(embeddedLinks);
    return links;
  }
1124213
public static LinkRelation parse(String relation) {

		return LINK_RELATIONS.stream() //
				.filter(it -> it.value().equalsIgnoreCase(relation)) //
				.findFirst() //
				.orElseThrow(() -> new IllegalArgumentException(relation + " is not a valid IANA link relation!"));
	}
231760
private function fillRelationshipAsSingleResource($data, $relationship, $key)
    {
        $data['data']['relationships'][$key] = $relationship[0];

        if ($this->shouldIncludeLinks()) {
            $data['data']['relationships'][$key] = array_merge([
                'links' => [
                    'self' => "{$this->baseUrl}/{$data['data']['type']}/{$data['data']['id']}/relationships/$key",
                    'related' => "{$this->baseUrl}/{$data['data']['type']}/{$data['data']['id']}/$key",
                ],
            ], $data['data']['relationships'][$key]);

            return $data;
        }
        return $data;
    }
1176897
def map_relations
      self.resource_relations = {}
      model.alchemy_resource_relations.each do |name, options|
        name = name.to_s.gsub(/_id$/, '') # ensure that we don't have an id
        association = association_from_relation_name(name)
        foreign_key = association.options[:foreign_key] || "#{association.name}_id".to_sym
        resource_relations[foreign_key] = options.merge(model_association: association, name: name)
      end
    end
421952
public function addRelation(Relation $relation) {
        $relation->setPrimaryModel($this);

        $this->_relations[$relation->getAlias()] = $relation;
        $this->_aliases[$relation->getRelatedClass()] = $relation->getAlias();
        $this->reserved[] = $relation->getAlias();

        $this->on('relation', $relation);

        return $this;
    }
576602
public function embedsOne($parent, string $relatedClass, string $relation = null): EmbedsOne
    {
        if (is_null($relation)) {
            list(, $caller) = debug_backtrace(false);
            $relation = $caller['function'];
        }

        $this->addEmbeddedRelation($relation);
        $this->addNonProxyRelation($relation);

        return new EmbedsOne($parent, $relatedClass, $relation);
    }
527313
public function embed(&$collection, $relations, $options = [])
    {
        $expanded = [];
        $relations = $this->expand($relations);
        $tree = $this->treeify($relations);

        $habtm = [];

        foreach ($tree as $name => $subtree) {
            $rel = $this->relation($name);
            if ($rel->type() === 'hasManyThrough') {
                $habtm[] = $name;
                continue;
            }

            $to = $rel->to();
            $query = empty($relations[$name]) ? [] : $relations[$name];
            if (is_callable($query)) {
                $options['query']['handler'] = $query;
            } else {
                $options['query'] = $query;
            }
            $related = $rel->embed($collection, $options);

            $subrelations = [];
            foreach ($relations as $path => $value) {
                if (preg_match('~^'.$name.'\.(.*)$~', $path, $matches)) {
                    $subrelations[$matches[1]] = $value;
                }
            }
            if ($subrelations) {
                $to::definition()->embed($related, $subrelations, $options);
            }
        }

        foreach ($habtm as $name) {
            $rel = $this->relation($name);
            $related = $rel->embed($collection, $options);
        }
    }
346315
public Clustering<Model> run(Relation<O> relation) {
    final int size = relation.size();
    if(size < minpts) {
      Clustering<Model> result = new Clustering<>("DBSCAN Clustering", "dbscan-clustering");
      result.addToplevelCluster(new Cluster<Model>(relation.getDBIDs(), true, ClusterModel.CLUSTER));
      return result;
    }

    RangeQuery<O> rangeQuery = QueryUtil.getRangeQuery(relation, getDistanceFunction());
    resultList = new ArrayList<>();
    noise = DBIDUtil.newHashSet();
    runDBSCAN(relation, rangeQuery);

    double averagen = ncounter / (double) relation.size();
    LOG.statistics(new DoubleStatistic(DBSCAN.class.getName() + ".average-neighbors", averagen));
    if(averagen < 1 + 0.1 * (minpts - 1)) {
      LOG.warning("There are very few neighbors found. Epsilon may be too small.");
    }
    if(averagen > 100 * minpts) {
      LOG.warning("There are very many neighbors found. Epsilon may be too large.");
    }

    Clustering<Model> result = new Clustering<>("DBSCAN Clustering", "dbscan-clustering");
    for(ModifiableDBIDs res : resultList) {
      result.addToplevelCluster(new Cluster<Model>(res, ClusterModel.CLUSTER));
    }
    result.addToplevelCluster(new Cluster<Model>(noise, true, ClusterModel.CLUSTER));
    return result;
  }
359459
public static Related with(CanonicalPath entityPath, String relationship) {
        return new Related(entityPath, relationship, EntityRole.SOURCE);
    }
1122685
public function withRelationshipSelfLink($resource, string $relationshipName): EncoderInterface
    {
        $link = $this
            ->getSchemaContainer()->getSchema($resource)
            ->getRelationshipSelfLink($resource, $relationshipName);

        return $this->withLinks([
            LinkInterface::SELF => $link,
        ]);
    }
40480
protected function getHasRelationQuery($relation, $entity)
    {
        return Relationship::noConstraints(function () use ($relation, $entity) {
            return $this->entityMap->$relation($entity);
        });
    }
1091524
@JsonCreator
	private static HalLinkRelation of(String relation) {

		String[] split = relation.split(":");

		String curie = split.length == 1 ? null : split[0];
		String localPart = split.length == 1 ? split[0] : split[1];

		return new HalLinkRelation(curie, localPart);
	}
33056
@Override
	public LinkRelation getCollectionResourceRelFor(Class<?> resource) {

		LookupContext context = LookupContext.forCollectionResourceRelLookup(entityType);

		return providers.getRequiredPluginFor(context).getCollectionResourceRelFor(resource);
	}
122071
def extract_relationships(cls, fields, resource, resource_instance):
        
        # Avoid circular deps
        from rest_framework_json_api.relations import ResourceRelatedField

        data = OrderedDict()

        # Don't try to extract relationships from a non-existent resource
        if resource_instance is None:
            return

        for field_name, field in six.iteritems(fields):
            # Skip URL field
            if field_name == api_settings.URL_FIELD_NAME:
                continue

            # don't output a key for write only fields
            if fields[field_name].write_only:
                continue

            # Skip fields without relations
            if not isinstance(
                field, (relations.RelatedField, relations.ManyRelatedField, BaseSerializer)
            ):
                continue

            source = field.source
            relation_type = utils.get_related_resource_type(field)

            if isinstance(field, relations.HyperlinkedIdentityField):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue
                # special case for HyperlinkedIdentityField
                relation_data = list()

                # Don't try to query an empty relation
                relation_queryset = relation_instance \
                    if relation_instance is not None else list()

                for related_object in relation_queryset:
                    relation_data.append(
                        OrderedDict([
                            ('type', relation_type),
                            ('id', encoding.force_text(related_object.pk))
                        ])
                    )

                data.update({field_name: {
                    'links': {
                        "related": resource.get(field_name)},
                    'data': relation_data,
                    'meta': {
                        'count': len(relation_data)
                    }
                }})
                continue

            relation_data = {}
            if isinstance(field, HyperlinkedMixin):
                field_links = field.get_links(resource_instance, field.related_link_lookup_field)
                relation_data.update({'links': field_links} if field_links else dict())
                data.update({field_name: relation_data})

            if isinstance(field, (ResourceRelatedField, )):
                if not isinstance(field, SkipDataMixin):
                    relation_data.update({'data': resource.get(field_name)})

                data.update({field_name: relation_data})
                continue

            if isinstance(
                    field, (relations.PrimaryKeyRelatedField, relations.HyperlinkedRelatedField)
            ):
                resolved, relation = utils.get_relation_instance(
                    resource_instance, '%s_id' % source, field.parent
                )
                if not resolved:
                    continue
                relation_id = relation if resource.get(field_name) else None
                relation_data = {
                    'data': (
                        OrderedDict([
                            ('type', relation_type), ('id', encoding.force_text(relation_id))
                        ])
                        if relation_id is not None else None)
                }

                if (
                    isinstance(field, relations.HyperlinkedRelatedField) and
                    resource.get(field_name)
                ):
                    relation_data.update(
                        {
                            'links': {
                                'related': resource.get(field_name)
                            }
                        }
                    )
                data.update({field_name: relation_data})
                continue

            if isinstance(field, relations.ManyRelatedField):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue

                relation_data = {}

                if isinstance(resource.get(field_name), Iterable):
                    relation_data.update(
                        {
                            'meta': {'count': len(resource.get(field_name))}
                        }
                    )

                if isinstance(field.child_relation, ResourceRelatedField):
                    # special case for ResourceRelatedField
                    relation_data.update(
                        {'data': resource.get(field_name)}
                    )

                if isinstance(field.child_relation, HyperlinkedMixin):
                    field_links = field.child_relation.get_links(
                        resource_instance,
                        field.child_relation.related_link_lookup_field
                    )
                    relation_data.update(
                        {'links': field_links}
                        if field_links else dict()
                    )

                    data.update({field_name: relation_data})
                    continue

                relation_data = list()
                for nested_resource_instance in relation_instance:
                    nested_resource_instance_type = (
                        relation_type or
                        utils.get_resource_type_from_instance(nested_resource_instance)
                    )

                    relation_data.append(OrderedDict([
                        ('type', nested_resource_instance_type),
                        ('id', encoding.force_text(nested_resource_instance.pk))
                    ]))
                data.update({
                    field_name: {
                        'data': relation_data,
                        'meta': {
                            'count': len(relation_data)
                        }
                    }
                })
                continue

            if isinstance(field, ListSerializer):
                resolved, relation_instance = utils.get_relation_instance(
                    resource_instance, source, field.parent
                )
                if not resolved:
                    continue

                relation_data = list()

                serializer_data = resource.get(field_name)
                resource_instance_queryset = list(relation_instance)
                if isinstance(serializer_data, list):
                    for position in range(len(serializer_data)):
                        nested_resource_instance = resource_instance_queryset[position]
                        nested_resource_instance_type = (
                            relation_type or
                            utils.get_resource_type_from_instance(nested_resource_instance)
                        )

                        relation_data.append(OrderedDict([
                            ('type', nested_resource_instance_type),
                            ('id', encoding.force_text(nested_resource_instance.pk))
                        ]))

                    data.update({field_name: {'data': relation_data}})
                    continue

            if isinstance(field, Serializer):
                relation_instance_id = getattr(resource_instance, source + "_id", None)
                if not relation_instance_id:
                    resolved, relation_instance = utils.get_relation_instance(
                        resource_instance, source, field.parent
                    )
                    if not resolved:
                        continue

                    if relation_instance is not None:
                        relation_instance_id = relation_instance.pk

                data.update({
                    field_name: {
                        'data': (
                            OrderedDict([
                                ('type', relation_type),
                                ('id', encoding.force_text(relation_instance_id))
                            ]) if resource.get(field_name) else None)
                    }
                })
                continue

        return utils._format_object(data)
188224
public Link getRequiredLink(String relation) {

		return getLink(relation) //
				.orElseThrow(() -> new IllegalArgumentException(String.format("No link with rel %s found!", relation)));
	}
142525
public function loadRelation($relation)
    {
        //If the node isn't already loaded
        if(!isset($this->relationProxyCache[$relation->getId()]))
        {
            //Create a proxy entity
            $em = $this;
            $entity = $this->proxyFactory->fromRelation($relation, $this->metaRepository, function ($node) use ($em) {
                return $em->loadNode($node);
            });

            $this->relationProxyCache[$relation->getId()] = $entity;
            $this->everymanRelationCache[$this->getHash($entity)] = $relation;
        }

        return $this->relationProxyCache[$relation->getId()];
    }