Specifies a filter for entities that are targets of a relationship with the specified entity.

@param entityPath the entity that is the source of the relationship
@param relationship the name of the relationship
@return a new "related" filter instance
171649
public static Related asTargetWith(CanonicalPath entityPath, String relationship) {
        return new Related(entityPath, relationship, EntityRole.TARGET);
    }
1094884
public Set<RelationshipTuple> getRelationships(PredicateNode predicate,
                                                   ObjectNode object) {
        return getRelationships(PID.toURIReference(m_pid), predicate, object);
    }
845654
@Description("apoc.index.relationships('TYPE','prop:value*') YIELD rel - lucene query on relationship index with the given type name")
    @Procedure(mode = Mode.READ)
    public Stream<WeightedRelationshipResult> relationships(@Name("type") String type, @Name("query") String query) throws Exception {
        if (!db.index().existsForRelationships(type)) return Stream.empty();
        return toWeightedRelationshipResult(db.index().forRelationships(type).query(query,null,null));
    }
953212
protected function createRelationship(RelationshipAnnotation $annotation, \ReflectionProperty $property): Relationship
    {
        $name = ($annotation->name === null)
            ? $property->getName()
            : $annotation->name;

        $type = $this->resolveType($annotation);

        $getter = ($annotation->getter === null)
            ? $this->resolveGetter($property)
            : $annotation->getter;

        $relationship = new Relationship($name, $type, $getter);
        $relationship->setPropertyName($property->getName());

        $this->handleLinks($annotation, $relationship);
        $this->handleDataControl($annotation, $relationship);

        return $relationship;
    }
705923
public void modifyRelationship(Relationship relationship, String description, String technology) {
        if (relationship == null) {
            throw new IllegalArgumentException("A relationship must be specified.");
        }

        Relationship newRelationship = new Relationship(relationship.getSource(), relationship.getDestination(), description, technology, relationship.getInteractionStyle());
        if (!relationship.getSource().has(newRelationship)) {
            relationship.setDescription(description);
            relationship.setTechnology(technology);
        } else {
            throw new IllegalArgumentException("This relationship exists already: " + newRelationship);
        }
    }
826947
public void setRelatedFindingsProductArn(java.util.Collection<StringFilter> relatedFindingsProductArn) {
        if (relatedFindingsProductArn == null) {
            this.relatedFindingsProductArn = null;
            return;
        }

        this.relatedFindingsProductArn = new java.util.ArrayList<StringFilter>(relatedFindingsProductArn);
    }
1012797
protected function createSingleIdentifierRelationship($object, RelationshipDefinition $definition, MappingContext $context): AbstractRelationship
    {
        $relatedObject = $object->{$definition->getGetter()}();

        if ($relatedObject === null) {
            return new NoDataRelationship();
        }

        $resource = $context->getMapper()->toResourceIdentifier($relatedObject);

        return new SingleIdentifierRelationship($resource);
    }
673469
@SuppressWarnings("unchecked")
	private Set<Resource> lookupRelationshipField(Collection<Resource> sourceResources, ResourceField relationshipField, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider,
			Map<ResourceIdentifier, Resource> resourceMap, Map<ResourceIdentifier, Object> entityMap) {
		if (sourceResources.isEmpty()) {
			return Collections.emptySet();
		}

		ResourceInformation resourceInformation = relationshipField.getParentResourceInformation();
		RegistryEntry registyEntry = resourceRegistry.getEntry(resourceInformation.getResourceType());

		List<Serializable> resourceIds = getIds(sourceResources, resourceInformation);

		boolean isMany = Iterable.class.isAssignableFrom(relationshipField.getType());
		Class<?> relationshipFieldClass = relationshipField.getElementType();

		Set<Resource> loadedTargets = new HashSet<>();

		@SuppressWarnings("rawtypes")
		RelationshipRepositoryAdapter relationshipRepository = registyEntry.getRelationshipRepositoryForClass(relationshipFieldClass, parameterProvider);
		if (relationshipRepository != null) {
			Map<Object, JsonApiResponse> responseMap;
			if (isMany) {
				responseMap = relationshipRepository.findBulkManyTargets(resourceIds, relationshipField, queryAdapter);
			} else {
				responseMap = relationshipRepository.findBulkOneTargets(resourceIds, relationshipField, queryAdapter);
			}

			for (Resource sourceResource : sourceResources) {
				Serializable sourceId = resourceInformation.parseIdString(sourceResource.getId());
				JsonApiResponse targetResponse = responseMap.get(sourceId);
				if (targetResponse != null && targetResponse.getEntity() != null) {
					Object targetEntity = targetResponse.getEntity();

					List<Resource> targets = setupRelation(sourceResource, relationshipField, targetEntity, queryAdapter, resourceMap, entityMap);
					loadedTargets.addAll(targets);
				} else {
					Nullable<Object> emptyData = Nullable.of(Iterable.class.isAssignableFrom(relationshipField.getType()) ? (Object) Collections.emptyList() : null);
					Relationship relationship = sourceResource.getRelationships().get(relationshipField.getJsonName());
					relationship.setData(emptyData);
				}
			}
		}

		return loadedTargets;
	}
929761
private Set<Resource> extractRelationshipField(List<Resource> sourceResources, ResourceField relationshipField, QueryAdapter queryAdapter, Map<ResourceIdentifier, Resource> resourceMap,
			Map<ResourceIdentifier, Object> entityMap, boolean lookUp) {
		Set<Resource> loadedEntities = new HashSet<>();
		for (Resource sourceResource : sourceResources) {
			ResourceIdentifier id = sourceResource.toIdentifier();

			Object source = entityMap.get(id);
			if (source != null && !(source instanceof Resource)) {
				Object targetEntity = PropertyUtils.getProperty(source, relationshipField.getUnderlyingName());

				if (!lookUp && Iterable.class.isAssignableFrom(relationshipField.getType()) && targetEntity == null) {
					throw new InternalServerErrorException(id + " relationship field collection '" + relationshipField.getJsonName() + "' can not be null. Either set the relationship as an empty "
							+ Iterable.class.getCanonicalName() + " or add annotation @" + JsonApiLookupIncludeAutomatically.class.getCanonicalName());
				}
				if (targetEntity == null) {
					continue;
				}
				List<Resource> targetIds = setupRelation(sourceResource, relationshipField, targetEntity, queryAdapter, resourceMap, entityMap);
				loadedEntities.addAll(targetIds);
			}
		}
		return loadedEntities;
	}
367677
@Override
    public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata)
    {
        // taking field's type as foreign entity, ignoring "targetEntity"
        Class<?> targetEntity = relationField.getType();

        ManyToOne ann = relationField.getAnnotation(ManyToOne.class);
        Relation relation = new Relation(relationField, targetEntity, null, ann.fetch(), Arrays.asList(ann.cascade()),
                ann.optional(), null, // mappedBy is null
                Relation.ForeignKey.MANY_TO_ONE);

        boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);

        if (relationField.isAnnotationPresent(AssociationOverride.class))
        {
            AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);
            JoinColumn[] joinColumns = annotation.joinColumns();

            relation.setJoinColumnName(joinColumns[0].name());

        }
        else if (isJoinedByFK)
        {
            JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);
            relation.setJoinColumnName(StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName()
                    : joinColumnAnn.name());
        }
        else
        {
            relation.setJoinColumnName(relationField.getName());
        }

        relation.setBiDirectionalField(metadata.getEntityClazz());
        metadata.addRelation(relationField.getName(), relation);

    }
692145
public Project.Storepoints.Storepoint.Relationships.Relationship createProjectStorepointsStorepointRelationshipsRelationship()
   {
      return new Project.Storepoints.Storepoint.Relationships.Relationship();
   }
301332
protected static void applyRelationships(final ContentSpec contentSpec, final Map<Integer, Node> nodes,
            final Map<String, SpecTopic> targetTopics, final List<CSNodeWrapper> relationshipFromNodes, final List<Process> processes,
            final DataProviderFactory providerFactory) {
        // Apply the user defined relationships stored in the database
        for (final CSNodeWrapper node : relationshipFromNodes) {
            boolean initialContentTopic = node.getNodeType() == CommonConstants.CS_NODE_INITIAL_CONTENT_TOPIC;
            boolean level = EntityUtilities.isNodeALevel(node);

            // In 1.3 or lower initial content relationships were stored on the topic, however in 1.4+ they are now on the initial
            // content level, so do the migration here
            final SpecNodeWithRelationships fromNode;
            if (initialContentTopic) {
                final CSNodeWrapper parentNode = node.getParent();
                final SpecNodeWithRelationships parent = (SpecNodeWithRelationships) nodes.get(parentNode.getId());
                if (parent instanceof InitialContent) {
                    fromNode = parent;
                } else {
                    final Level parentLevel = (Level) parent;
                    if (parentLevel.getFirstSpecNode() instanceof InitialContent) {
                        fromNode = (SpecNodeWithRelationships) parentLevel.getFirstSpecNode();
                    } else {
                        fromNode = new InitialContent(parent.getLineNumber(), CSConstants.LEVEL_INITIAL_CONTENT + ":");
                        if (parentLevel.getChildNodes().isEmpty()) {
                            parentLevel.appendChild(fromNode);
                        } else {
                            parentLevel.insertBefore(fromNode, parentLevel.getChildNodes().get(0));
                        }
                    }
                }
            } else {
                fromNode = (SpecNodeWithRelationships) nodes.get(node.getId());
            }

            // Check if we have any relationships to process
            if (node.getRelatedToNodes() == null || node.getRelatedToNodes().isEmpty()) continue;
            final List<CSRelatedNodeWrapper> relatedToNodes = node.getRelatedToNodes().getItems();

            // Sort the relationships into the correct order based on the sort variable
            Collections.sort(relatedToNodes, new CSRelatedNodeSorter());

            // Add the relationships to the topic
            for (final CSRelatedNodeWrapper relatedToNode : relatedToNodes) {
                final Node toNode = nodes.get(relatedToNode.getId());
                if (toNode == null) {
                    throw new IllegalStateException("The related node does not exist in the content specification");
                } else if (toNode instanceof Level) {
                    // Relationships to levels
                    final Level toLevel = (Level) toNode;

                    // Ensure that the level has a target id if not create one.
                    if (toLevel.getTargetId() == null) {
                        toLevel.setTargetId("T00" + relatedToNode.getId());
                    }

                    // Add the relationship
                    fromNode.addRelationshipToTarget(toLevel, RelationshipType.getRelationshipType(relatedToNode.getRelationshipType()),
                            initialContentTopic || level ? null : toLevel.getTitle());
                } else {
                    // Relationships to topics
                    final SpecTopic toSpecTopic = (SpecTopic) toNode;
                    final String title = toSpecTopic.getTitle();

                    // Add the relationship
                    if (relatedToNode.getRelationshipMode().equals(CommonConstants.CS_RELATIONSHIP_MODE_TARGET)) {
                        fromNode.addRelationshipToTarget(toSpecTopic,
                                RelationshipType.getRelationshipType(relatedToNode.getRelationshipType()),
                                initialContentTopic || level ? null : title);
                    } else {
                        fromNode.addRelationshipToTopic(toSpecTopic,
                                RelationshipType.getRelationshipType(relatedToNode.getRelationshipType()),
                                initialContentTopic || level ? null : title);
                    }
                }
            }
        }

        // Create the unique id map
        final Map<String, SpecTopic> uniqueIdSpecTopicMap = ContentSpecUtilities.getUniqueIdSpecTopicMap(contentSpec);

        // Apply the process relationships
        for (final Process process : processes) {
            process.processTopics(uniqueIdSpecTopicMap, targetTopics, providerFactory.getProvider(TopicProvider.class),
                    providerFactory.getProvider(ServerSettingsProvider.class));
        }
    }
540291
public com.google.api.ads.adwords.axis.v201809.cm.RelationshipType getRelationshipType() {
        return relationshipType;
    }
1007476
public function createReadRelationshipBuilder(
        string $relationshipName,
        iterable $relationshipFilters = null,
        iterable $relationshipSorts = null,
        iterable $columns = null
    ): ModelQueryBuilder {
        assert(
            $this->getModelSchemas()->hasRelationship($this->getModelClass(), $relationshipName),
            "Relationship `$relationshipName` do not exist in model `" . $this->getModelClass() . '`'
        );

        // as we read data from a relationship our main table and model would be the table/model in the relationship
        // so 'root' model(s) will be located in the reverse relationship.

        list ($targetModelClass, $reverseRelName) =
            $this->getModelSchemas()->getReverseRelationship($this->getModelClass(), $relationshipName);

        $builder = $this
            ->createBuilder($targetModelClass)
            ->selectModelColumns($columns)
            ->fromModelTable();

        // 'root' filters would be applied to the data in the reverse relationship ...
        if ($this->hasFilters() === true) {
            $filters = $this->getFilters();
            $sorts   = $this->getSorts();
            $joinCondition = $this->areFiltersWithAnd() === true ? ModelQueryBuilder::AND : ModelQueryBuilder::OR;
            $builder->addRelationshipFiltersAndSorts($reverseRelName, $filters, $sorts, $joinCondition);
        }
        // ... and the input filters to actual data we select
        if ($relationshipFilters !== null) {
            $builder->addFiltersWithAndToAlias($relationshipFilters);
        }
        if ($relationshipSorts !== null) {
            $builder->addSorts($relationshipSorts);
        }

        $this->applyPaging($builder);

        // While joining tables we select distinct rows.
        $builder->distinct();

        return $this->builderOnReadRelationship($builder);
    }
537862
@Override
    public boolean match(Statement s) {
        if (s.getObject() == null) {
            return false;
        }
        if (s.getObject().getTerm() == null) {
            return false;
        }
        final RelationshipType r = s.getRelationshipType();
        if (!r.isDirected()) {
            return true;
        }
        return false;
    }
928754
private void setRelationToEntity(Object entity, Object relationEntity, Relation relation)
    {
        if (relation.getTargetEntity().isAssignableFrom(getEntity(relationEntity).getClass()))
        {

            if (relation.isUnary())
            {
                PropertyAccessorHelper.set(entity, relation.getProperty(), getEntity(relationEntity));
            }
            else
            {
                Object associationObject = PropertyAccessorHelper.getObject(entity, relation.getProperty());
                if (associationObject == null || ProxyHelper.isProxyOrCollection(associationObject))
                {
                    associationObject = PropertyAccessorHelper.getCollectionInstance(relation.getProperty());
                    PropertyAccessorHelper.set(entity, relation.getProperty(), associationObject);
                }

                ((Collection) associationObject).add(getEntity(relationEntity));
            }
        }
    }
457835
@SuppressWarnings("unchecked")
	public Result<Set<Resource>> lookupRelatedResource(IncludeRequest request, Collection<Resource> sourceResources,
													   ResourceField relationshipField) {
		if (sourceResources.isEmpty()) {
			return resultFactory.just(Collections.emptySet());
		}

		// directly load where relationship data is available
		Collection<Resource> sourceResourcesWithData = new ArrayList<>();
		Collection<Resource> sourceResourcesWithoutData = new ArrayList<>();

		for (Resource sourceResource : sourceResources) {
			boolean present = sourceResource.getRelationships().get(relationshipField.getJsonName()).getData().isPresent();
			if (present) {
				sourceResourcesWithData.add(sourceResource);
			} else {
				sourceResourcesWithoutData.add(sourceResource);
			}

		}

		Set<Resource> relatedResources = new HashSet<>();


		Result<Set<Resource>> result = resultFactory.just(relatedResources);
		if (!sourceResourcesWithData.isEmpty()) {
			Result<Set<Resource>> lookupWithId = lookupRelatedResourcesWithId(request, sourceResourcesWithData,
					relationshipField);
			result = result.zipWith(lookupWithId, this::mergeList);
		}
		if (!sourceResourcesWithoutData.isEmpty()) {
			Result<Set<Resource>> lookupWithoutData = lookupRelatedResourceWithRelationship(request, sourceResourcesWithoutData,
					relationshipField);
			result = result.zipWith(lookupWithoutData, this::mergeList);
		}
		return result;
	}