Returns compiled relationship definitions
969264
def compiled_relationships(self):
        """"""

        def get_column_args(column):
            tmp = []
            for arg_name, arg_val in column.items():
                if arg_name not in ('name', 'type', 'reference', 'class'):
                    if arg_name in ('back_populates', ):
                        arg_val = "'{}'".format(arg_val)
                    tmp.append(ALCHEMY_TEMPLATES.column_arg.safe_substitute(arg_name=arg_name,
                                                                            arg_val=arg_val))
            return ", ".join(tmp)

        res = []
        for column in self.relationship_definitions:
            column_args = get_column_args(column)
            column_name = column.get('name')
            cls_name = column.get("class")
            res.append(
                ALCHEMY_TEMPLATES.relationship.safe_substitute(column_name=column_name,
                                                               column_args=column_args,
                                                               class_name=cls_name))
        join_string = "\n" + self.tab
        return join_string.join(res)
1188425
private Map<String, Object> getPersistedRelations(Object relationEntity)
    {
        return relationEntity != null && relationEntity.getClass().isAssignableFrom(EnhanceEntity.class) ? ((EnhanceEntity) relationEntity)
                .getRelations() : null;
    }
971678
def cache_relationships(self, cache_super=True, cache_sub=True):
        
        return self.get_queryset().cache_relationships(cache_super=cache_super, cache_sub=cache_sub)
590933
def _get_to_many_relationship_value(self, obj, column):
        
        related_key = column.get('related_key', None)

        related = getattr(obj, column['__col__'].key)
        value = {}
        if related:
            total = len(related)
            for index, rel_obj in enumerate(related):
                if related_key:
                    compiled_res = self._get_formatted_val(
                        rel_obj, related_key, column
                    )
                else:
                    compiled_res = column['__prop__'].compile_obj(
                        rel_obj
                    )
                value['item_%d' % index] = compiled_res
                value[str(index)] = compiled_res
                value["_" + str(index)] = compiled_res

                if index == 0:
                    value['first'] = compiled_res

                if index == total - 1:
                    value['last'] = compiled_res

        return value
1040729
function getRelationships(model) {
    const modelName = model.constructor.name;
    const properties = typed_conversions_1.hashToArray(exports.relationshipsByModel[modelName], "property") || [];
    let parent = Object.getPrototypeOf(model.constructor);
    while (parent.name) {
        const subClass = new parent();
        const subClassName = subClass.constructor.name;
        properties.push(...typed_conversions_1.hashToArray(exports.relationshipsByModel[subClassName], "property"));
        parent = Object.getPrototypeOf(subClass.constructor);
    }
    return properties;
}
1185261
def related_schema(self):
        
        relationship_field = self.name

        if relationship_field not in get_relationships(self.schema):
            raise InvalidFilters("{} has no relationship attribute {}".format(self.schema.__name__, relationship_field))

        return self.schema._declared_fields[relationship_field].schema.__class__
797977
def cache_relationships(self, cache_super=True, cache_sub=True):
        
        relationships_to_cache = compress(
            ['super_relationships__super_entity', 'sub_relationships__sub_entity'], [cache_super, cache_sub])
        return self.prefetch_related(*relationships_to_cache)
1234868
private static void addRelationPropertyDefinitions(RelationshipTypeDefinitionImpl type) {

        type.addPropertyDefinition(
            createPropDef(
                PropertyIds.SOURCE_ID,
                "Source",
                "Source",
                PropertyType.ID,
                Cardinality.SINGLE,
                Updatability.ONCREATE,
                false,
                true));

        type.addPropertyDefinition(
            createPropDef(
                PropertyIds.TARGET_ID,
                "Target",
                "Target",
                PropertyType.ID,
                Cardinality.SINGLE,
                Updatability.ONCREATE,
                false,
                true));

    }
897275
def get_type_data(self, name):
        """"""
        try:
            return {
                'authority': 'DLKIT',
                'namespace': 'relationship.Relationship',
                'identifier': name.lower(),
                'domain': 'Generic Types',
                'display_name': name.title() + ' Type',
                'display_label': name.title(),
                'description': ('The ' + name.title() + ' Type.')
            }
        except IndexError:
            raise NotFound('RelationshipType: ' + name.title())
1224979
def relations_used(self):
        
        g = self.get_graph()
        types = set()
        for (x,y,d) in g.edges(data=True):
            types.add(d['pred'])
        return list(types)
1160427
def apply_relationships(self, data, obj):
        
        relationships_to_apply = []
        relationship_fields = get_relationships(self.resource.schema, model_field=True)
        for key, value in data.items():
            if key in relationship_fields:
                related_model = getattr(obj.__class__, key).property.mapper.class_
                schema_field = get_schema_field(self.resource.schema, key)
                related_id_field = self.resource.schema._declared_fields[schema_field].id_field

                if isinstance(value, list):
                    related_objects = []

                    for identifier in value:
                        related_object = self.get_related_object(related_model, related_id_field, {'id': identifier})
                        related_objects.append(related_object)

                    relationships_to_apply.append({'field': key, 'value': related_objects})
                else:
                    related_object = None

                    if value is not None:
                        related_object = self.get_related_object(related_model, related_id_field, {'id': value})

                    relationships_to_apply.append({'field': key, 'value': related_object})

        for relationship in relationships_to_apply:
            setattr(obj, relationship['field'], relationship['value'])
1187734
protected static function _initRelationships()
    {
        $className = get_called_class();
        if (!empty(static::$_classRelationships[$className])) {
            $relationships = [];
            foreach (static::$_classRelationships[$className] as $relationship => $options) {
                if (is_array($options)) {
                    $relationships[$relationship] = static::_initRelationship($relationship, $options);
                }
            }
            static::$_classRelationships[$className] = $relationships;
        }
    }
758944
function handleIncludes (resp, includes, relations, options) {
  var app = options.app

  relations = utils.setIncludedRelations(relations, app)

  var resources = _.isArray(resp.data) ? resp.data : [resp.data]

  if (typeof includes === 'string') {
    includes = [includes]
  }

  if (!_.isArray(includes)) {
    throw RelUtils.getInvalidIncludesError(
      'JSON API unable to detect valid includes'
    )
  }

  var embedded = resources.map(function subsituteEmbeddedForIds (resource) {
    return includes.map(function (include) {
      var relation = relations[include]
      var includedRelations = relations[include].relations
      var propertyKey = relation.keyFrom
      var plural = ''
      if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) {
        var descriminator = relation.polymorphic.discriminator
        var discriminator = resource.attributes[descriminator]
        plural = utils.pluralForModel(app.models[discriminator])
      } else {
        plural = utils.pluralForModel(relation.modelTo)
      }
      var embeds = []

      // If relation is belongsTo then pk and fk are the other way around
      if (utils.relationFkOnModelFrom(relation)) {
        propertyKey = relation.keyTo
      }

      if (!relation) {
        throw RelUtils.getInvalidIncludesError(
          'Can\'t locate relationship "' + include + '" to include'
        )
      }

      resource.relationships[include] = resource.relationships[include] || {}

      if (resource.relationships[include] && resource.attributes[include]) {
        if (_.isArray(resource.attributes[include])) {
          embeds = resource.attributes[include].map(function (rel) {
            rel = utils.clone(rel)
            return createCompoundIncludes(
              rel,
              propertyKey,
              relation.keyTo,
              plural,
              includedRelations,
              options
            )
          })
          embeds = _.compact(embeds)
          const included = resource.attributes[include]
          resource.relationships[include].data = included.map(relData => {
            return {
              id: String(relData[propertyKey]),
              type: plural
            }
          })
        } else {
          var rel = utils.clone(resource.attributes[include])
          var compoundIncludes = createCompoundIncludes(
            rel,
            propertyKey,
            relation.keyFrom,
            plural,
            includedRelations,
            options
          )

          resource.relationships[include].data = {
            id: String(resource.attributes[include][propertyKey]),
            type: plural
          }
          embeds.push(compoundIncludes)
        }
        delete resource.attributes[relation.keyFrom]
        delete resource.attributes[relation.keyTo]
        delete resource.attributes[include]
      }
      return embeds
    })
  })

  if (embedded.length) {
    // This array may contain duplicate models if the same item is referenced multiple times in 'data'
    var duplicate = _.flattenDeep(embedded)
    // So begin with an empty array that will only contain unique items
    var unique = []
    // Iterate through each item in the first array
    duplicate.forEach(function (d) {
      // Count the number of items in the unique array with matching 'type' AND 'id'
      // Since we're adhering to the JSONAPI spec, both 'type' and 'id' can assumed to be present
      // Both 'type' and 'id' are needed for comparison because we could theoretically have objects of different
      // types who happen to have the same 'id', and those would not be considered duplicates
      var count = unique.filter(function (u) {
        return u.type === d.type && u.id === d.id
      }).length
      // If there are no matching entries, then add the item to the unique array
      if (count === 0) {
        unique.push(d)
      }
    })
    resp.included = unique
  }
}
959160
def get_relationship_type(options)
      keys = options.keys.collect{|k|k.to_s}
      key = keys.find{|k| ['parent','child','spouse'].include? k} 
      key
    end
98374
private Set<RelationshipTuple> getRels(String relsDatastreamName) {
        List<Datastream> relsDatastreamVersions = m_datastreams.get(relsDatastreamName);

        if (relsDatastreamVersions == null || relsDatastreamVersions.size() == 0) {
            return new HashSet<RelationshipTuple>();
        }

        Datastream latestRels = relsDatastreamVersions.get(0);

        for (Datastream v : relsDatastreamVersions) {
           	if (v.DSCreateDT == null){
           		latestRels = v;
           		break;
           	}
            if (v.DSCreateDT.getTime() > latestRels.DSCreateDT.getTime()) {
                latestRels = v;
            }
        }

        try {
            return RDFRelationshipReader.readRelationships(latestRels);
        } catch (ServerException e) {
            throw new RuntimeException("Error reading object relationships in " + relsDatastreamName, e);
        }
    }
1256560
private void createRelationshipType(CmsRelationType relType) {

        // relationship types
        RelationshipTypeDefinitionImpl relationshipType = new RelationshipTypeDefinitionImpl();
        relationshipType.setBaseTypeId(BaseTypeId.CMIS_RELATIONSHIP);
        relationshipType.setParentTypeId(RELATIONSHIP_TYPE_ID);
        relationshipType.setIsControllableAcl(Boolean.FALSE);
        relationshipType.setIsControllablePolicy(Boolean.FALSE);
        relationshipType.setIsCreatable(Boolean.valueOf(!relType.isDefinedInContent()));
        relationshipType.setDescription(relType.getName());
        relationshipType.setDisplayName(relType.getName());
        relationshipType.setIsFileable(Boolean.FALSE);
        relationshipType.setIsIncludedInSupertypeQuery(Boolean.TRUE);
        relationshipType.setLocalName(relType.getName());
        relationshipType.setLocalNamespace(NAMESPACE);
        relationshipType.setIsQueryable(Boolean.FALSE);
        String id = "opencms:" + relType.getName().toUpperCase();
        relationshipType.setQueryName(id);
        relationshipType.setId(id);
        List<String> typeList = new ArrayList<String>();
        typeList.add("cmis:document");
        typeList.add("cmis:folder");
        relationshipType.setAllowedSourceTypes(typeList);
        relationshipType.setAllowedTargetTypes(typeList);
        addType(relationshipType);
    }
857387
def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type],
                                        None, None]:
    
    insp = inspect(obj)  # type: InstanceState
    # insp.mapper.relationships is of type
    # sqlalchemy.utils._collections.ImmutableProperties, which is basically
    # a sort of AttrDict.
    for attrname, rel_prop in insp.mapper.relationships.items():  # type: Tuple[str, RelationshipProperty]  # noqa
        # noinspection PyUnresolvedReferences
        related_class = rel_prop.mapper.class_
        # log.critical("gen_relationships: attrname={!r}, "
        #              "rel_prop={!r}, related_class={!r}, rel_prop.info={!r}",
        #              attrname, rel_prop, related_class, rel_prop.info)
        yield attrname, rel_prop, related_class