Create a relationship object for this attribute from the given
        relator and relationship direction.
174955
def make_relationship(self, relator,
                          direction=
                            RELATIONSHIP_DIRECTIONS.BIDIRECTIONAL):
        
        if IEntity.providedBy(relator): # pylint:disable=E1101
            rel = DomainRelationship(relator, self,
                                     direction=direction)
        elif IResource.providedBy(relator): # pylint:disable=E1101
            rel = ResourceRelationship(relator, self,
                                       direction=direction)
        else:
            raise ValueError('Invalid relator argument "%s" for '
                             'relationship; must provide IEntity or '
                             'IResource.' % relator)
        return rel
121673
void populateRelationForM2M(Object entity, EntityMetadata entityMetadata, PersistenceDelegator delegator,
            Relation relation, Object relObject, Map<String, Object> relationsMap)
    {
        // For M-M relationship of Collection type, relationship entities are
        // always fetched from Join Table.
        if (relation.getPropertyType().isAssignableFrom(List.class)
                || relation.getPropertyType().isAssignableFrom(Set.class))
        {
            if (relation.isRelatedViaJoinTable() && (relObject == null || ProxyHelper.isProxyOrCollection(relObject)))
            {
                populateCollectionFromJoinTable(entity, entityMetadata, delegator, relation);
            }

        }
        else if (relation.getPropertyType().isAssignableFrom(Map.class))
        {
            if (relation.isRelatedViaJoinTable())
            {
                // TODO: Implement Map relationships via Join Table (not
                // supported as of now)
            }
            else
            {
                populateCollectionFromMap(entity, delegator, relation, relObject, relationsMap);
            }
        }
    }
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;
}
142811
public function newFromBuilderRecursive(Model $model, array $attributes = [], Relation $parentRelation = null)
    {
        $instance = $model->newInstance([], $exists = true);

        // fill the instance attributes with checking
        $instance->unguard();
        $instance->fill($attributes);
        $instance->reguard();
        // Load relations recursive
        $this->loadRelationsAttributesRecursive($instance);

        // Load pivot
        $this->loadPivotAttribute($instance, $parentRelation);

        return $instance;
    }
1069485
def add_rel(self, rId, reltype, target, is_external=False):
        
        target_mode = RTM.EXTERNAL if is_external else RTM.INTERNAL
        relationship = CT_Relationship.new(rId, reltype, target, target_mode)
        self.append(relationship)
1000324
def add_rel(self, source_node_id, target_node_id, rel):
        

        # Add the relationship
        n1_ref = self.graph_db.get_indexed_node('Node', 'node_id', source_node_id)
        n2_ref = self.graph_db.get_indexed_node('Node', 'node_id', target_node_id)

        # Sanity check
        if not n1_ref or not n2_ref:
            print 'Cannot add relationship between unfound nodes: %s --> %s' % (source_node_id, target_node_id)
            return
        path = neo4j.Path(n1_ref, rel, n2_ref)
        path.get_or_create(self.graph_db)
1343302
def new(rId, reltype, target, target_mode=RTM.INTERNAL):
        
        xml = '<Relationship xmlns="%s"/>' % nsmap['pr']
        relationship = parse_xml(xml)
        relationship.set('Id', rId)
        relationship.set('Type', reltype)
        relationship.set('Target', target)
        if target_mode == RTM.EXTERNAL:
            relationship.set('TargetMode', RTM.EXTERNAL)
        return relationship
521762
def wordrelationships(relationshiplist):
    ''''''
    # Default list of relationships
    # FIXME: using string hack instead of making element
    #relationships = makeelement('Relationships', nsprefix='pr')
    relationships = etree.fromstring(
        '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006'
        '/relationships"></Relationships>')
    count = 0
    for relationship in relationshiplist:
        # Relationship IDs (rId) start at 1.
        rel_elm = makeelement('Relationship', nsprefix=None,
                              attributes={'Id':     'rId'+str(count+1),
                                          'Type':   relationship[0],
                                          'Target': relationship[1]}
                              )
        relationships.append(rel_elm)
        count += 1
    return relationships
497319
function( model, attr, options ) {
			// Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange)
			if ( this.isLocked() ) {
				return;
			}
			this.acquire();
			options = this.sanitizeOptions( options );
			
			// 'options._related' is set by 'addRelated'/'removeRelated'. If it is set, the change
			// is the result of a call from a relation. If it's not, the change is the result of 
			// a 'set' call on this.instance.
			var changed = _.isUndefined( options._related );
			var oldRelated = changed ? this.related : options._related;
			
			if ( changed ) {	
				this.keyContents = attr;
				
				// Set new 'related'
				if ( attr instanceof this.relatedModel ) {
					this.related = attr;
				}
				else if ( attr ) {
					var related = this.findRelated( options );
					this.setRelated( related );
				}
				else {
					this.setRelated( null );
				}
			}
			
			// Notify old 'related' object of the terminated relation
			if ( oldRelated && this.related !== oldRelated ) {
				_.each( this.getReverseRelations( oldRelated ), function( relation ) {
						relation.removeRelated( this.instance, options );
					}, this );
			}
			
			// Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated;
			// that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'.
			// In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet.
			_.each( this.getReverseRelations(), function( relation ) {
					relation.addRelated( this.instance, options );
				}, this);
			
			// Fire the 'update:<key>' event if 'related' was updated
			if ( !options.silentChange && this.related !== oldRelated ) {
				var dit = this;
				Backbone.Relational.eventQueue.add( function() {
					dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options );
				});
			}
			this.release();
		}
1326052
def add_relationship(self, reltype, target, rId, is_external=False):
        
        rel = _Relationship(rId, reltype, target, self._baseURI, is_external)
        self[rId] = rel
        if not is_external:
            self._target_parts_by_rId[rId] = target
        return rel
1089295
public void populateRelationshipProperties(EntityMetadata entityMetadata, EntityMetadata targetNodeMetadata,
            Relationship relationship, Object relationshipObj)
    {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());
        EntityType entityType = metaModel.entity(relationshipObj.getClass());

        Set<Attribute> attributes = entityType.getSingularAttributes();
        for (Attribute attribute : attributes)
        {
            Field f = (Field) attribute.getJavaMember();
            if (!f.getType().equals(entityMetadata.getEntityClazz())
                    && !f.getType().equals(targetNodeMetadata.getEntityClazz()))
            {
                EntityMetadata relMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                        relationshipObj.getClass());
                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
                if (metaModel.isEmbeddable(relMetadata.getIdAttribute().getBindableJavaType())
                        && ((SingularAttribute) attribute).isId())
                {
                    // Populate Embedded attribute value into relationship
                    Object id = PropertyAccessorHelper.getId(relationshipObj, relMetadata);
                    Object serializedIdValue = serializeIdAttributeValue(relMetadata, metaModel, id);
                    relationship.setProperty(columnName, serializedIdValue);

                    // Populate attributes of embedded fields into relationship
                    Set<Attribute> embeddableAttributes = metaModel.embeddable(
                            relMetadata.getIdAttribute().getBindableJavaType()).getSingularAttributes();
                    for (Attribute embeddableAttribute : embeddableAttributes)
                    {
                        String embeddedColumn = ((AbstractAttribute) embeddableAttribute).getJPAColumnName();
                        if (embeddedColumn == null)
                            embeddedColumn = embeddableAttribute.getName();
                        Object value = PropertyAccessorHelper
                                .getObject(id, (Field) embeddableAttribute.getJavaMember());

                        if (value != null)
                            relationship.setProperty(embeddedColumn, value);
                    }
                }
                else
                {
                    Object value = PropertyAccessorHelper.getObject(relationshipObj, f);
                    relationship.setProperty(columnName, toNeo4JProperty(value));
                }

            }
        }

    }
652277
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'relations' in _dict:
            args['relations'] = [
                QueryRelationsRelationship._from_dict(x)
                for x in (_dict.get('relations'))
            ]
        return cls(**args)
495491
def recreate_relationships(self, class_, attribute_name, key):
        '''
        
        '''
        iterable = self.record_keeper.foreign_to_many_foreign_map[key]
        for foreign_page_id, foreign_page_id_list in iteritems(iterable):

            # Assumption: local page has been indexed and exists
            # TODO: handle case where it doesn't exist
            local_page_id = self.record_keeper.get_local_page(foreign_page_id)
            local_page = Page.objects.get(id=local_page_id).specific

            for _foreign_page_id in foreign_page_id_list:
                try:
                    local_version_page_id = (self.record_keeper
                                             .get_local_page(_foreign_page_id))
                    foreign_page = Page.objects.get(
                        id=local_version_page_id).specific
                    realtionship_object = class_(page=local_page)
                    setattr(realtionship_object, attribute_name, foreign_page)
                    realtionship_object.save()
                except Exception as e:
                    context = {
                        "exception": e,
                        "function_schema": ("recreate_relationships"
                                            "(class, attribute_name, key)"),
                        "attribute_name": str(attribute_name),
                        "key": str(key),
                        "class": str(class_),
                        "foreign_page_id": str(foreign_page_id),
                    }
                    self.log(ERROR, "recreating relationships",
                             context=context)
590113
def extract_relation_instance(cls, field_name, field, resource_instance, serializer):
        
        relation_instance = None

        try:
            relation_instance = getattr(resource_instance, field_name)
        except AttributeError:
            try:
                # For ManyRelatedFields if `related_name` is not set
                # we need to access `foo_set` from `source`
                relation_instance = getattr(resource_instance, field.child_relation.source)
            except AttributeError:
                if hasattr(serializer, field.source):
                    serializer_method = getattr(serializer, field.source)
                    relation_instance = serializer_method(resource_instance)
                else:
                    # case when source is a simple remap on resource_instance
                    try:
                        relation_instance = getattr(resource_instance, field.source)
                    except AttributeError:
                        pass

        return relation_instance
1372874
def parse_relationship(document, xmlcontent, rel_type):
    

    doc = etree.fromstring(xmlcontent)

    for elem in doc:
        if elem.tag == _name('{{{pr}}}Relationship'):
            rel = {'target': elem.attrib['Target'],
                   'type': elem.attrib['Type'],
                   'target_mode': elem.attrib.get('TargetMode', 'Internal')}

            document.relationships[rel_type][elem.attrib['Id']] = rel
128098
protected void processRelationship(final ParserData parserData, final SpecNodeWithRelationships specNode,
            final Relationship relationship) {
        final String relatedId = relationship.getSecondaryRelationshipId();
        // The relationship points to a target so it must be a level or topic
        if (relatedId.toUpperCase(Locale.ENGLISH).matches(ProcessorConstants.TARGET_REGEX)) {
            if (parserData.getTargetTopics().containsKey(relatedId) && !parserData.getTargetLevels().containsKey(relatedId)) {
                specNode.addRelationshipToTarget(parserData.getTargetTopics().get(relatedId), relationship.getType(),
                        relationship.getRelationshipTitle());
            } else if (!parserData.getTargetTopics().containsKey(relatedId) && parserData.getTargetLevels().containsKey(relatedId)) {
                specNode.addRelationshipToTarget(parserData.getTargetLevels().get(relatedId), relationship.getType(),
                        relationship.getRelationshipTitle());
            } else {
                final SpecTopic dummyTopic = new SpecTopic(-1, "");
                dummyTopic.setTargetId(relatedId);
                dummyTopic.setUniqueId("-1");
                specNode.addRelationshipToTarget(dummyTopic, relationship.getType(), relationship.getRelationshipTitle());
            }
        }
        // The relationship isn't a target so it must point to a topic directly
        else {
            if (!CSConstants.NEW_TOPIC_ID_PATTERN.matcher(relatedId).matches()) {
                // The relationship isn't a unique new topic so it will contain the line number in front of
                // the topic ID
                if (!relatedId.startsWith("X")) {
                    int count = 0;
                    SpecTopic relatedTopic = null;

                    // Get the related topic and count if more then one is found
                    for (final Map.Entry<String, SpecTopic> specTopicEntry : parserData.getSpecTopics().entrySet()) {
                        if (specTopicEntry.getKey().matches("^[\\w\\d]+-" + relatedId + "$")) {
                            relatedTopic = specTopicEntry.getValue();
                            count++;
                        }
                    }

                    /*
                     * Add the relationship to the node even if the relationship isn't duplicated
                     * and the related topic isn't the current topic. This is so it shows up in the
                     * output.
                     */
                    if (count > 0) {
                        specNode.addRelationshipToTopic(relatedTopic, relationship.getType(), relationship.getRelationshipTitle());
                    } else {
                        final SpecTopic dummyTopic = new SpecTopic(-1, "");
                        dummyTopic.setId(relatedId);
                        dummyTopic.setUniqueId("-1");
                        specNode.addRelationshipToTopic(dummyTopic, relationship.getType(), relationship.getRelationshipTitle());
                    }
                } else {
                    final SpecTopic dummyTopic = new SpecTopic(-1, "");
                    dummyTopic.setId(relatedId);
                    dummyTopic.setUniqueId("-1");
                    specNode.addRelationshipToTopic(dummyTopic, relationship.getType(), relationship.getRelationshipTitle());
                }
            } else {
                if (parserData.getSpecTopics().containsKey(relatedId)) {
                    final SpecTopic relatedSpecTopic = parserData.getSpecTopics().get(relatedId);

                    // Check that a duplicate doesn't exist, because if it does the new topic isn't unique
                    String duplicatedId = "X" + relatedId.substring(1);
                    boolean duplicateExists = false;
                    for (String uniqueTopicId : parserData.getSpecTopics().keySet()) {
                        if (uniqueTopicId.matches("^[\\w\\d]+-" + duplicatedId + "$")) {
                            duplicateExists = true;
                            break;
                        }
                    }

                    if (relatedSpecTopic != specNode) {
                        if (!duplicateExists) {
                            specNode.addRelationshipToTopic(relatedSpecTopic, relationship.getType(), relationship.getRelationshipTitle());
                        } else {
                            // Only create a new target if one doesn't already exist
                            if (relatedSpecTopic.getTargetId() == null) {
                                String targetId = ContentSpecUtilities.generateRandomTargetId(relatedSpecTopic.getUniqueId());
                                while (parserData.getTargetTopics().containsKey(targetId) || parserData.getTargetLevels().containsKey(
                                        targetId)) {
                                    targetId = ContentSpecUtilities.generateRandomTargetId(relatedSpecTopic.getUniqueId());
                                }
                                parserData.getSpecTopics().get(relatedId).setTargetId(targetId);
                                parserData.getTargetTopics().put(targetId, relatedSpecTopic);
                            }
                            specNode.addRelationshipToTopic(relatedSpecTopic, relationship.getType(), relationship.getRelationshipTitle());
                        }
                    }
                } else {
                    final SpecTopic dummyTopic = new SpecTopic(-1, "");
                    dummyTopic.setId(relatedId);
                    dummyTopic.setUniqueId("-1");
                    specNode.addRelationshipToTopic(dummyTopic, relationship.getType(), relationship.getRelationshipTitle());
                }
            }
        }
    }
235774
RelationImpl buildRelation(EdgeElement edge, RelationType type, Role owner, Role value) {
        return getOrBuildConcept(edge, (e) -> RelationImpl.create(RelationEdge.create(type, owner, value, edge)));
    }