e.g. class Person will generate relationship for table Persons
518547
static function ClassHasMany($parentclass, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
	{
		$ar = new $parentclass();
		$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
	}
615255
private Set<Resource> fetchRelationFromEntity(IncludeRequest request, List<Resource> sourceResources, ResourceField
			relationshipField, boolean allowLookup, boolean fetchRelatedEntity, boolean mustInclude) {
		Set<Resource> loadedResources = new HashSet<>();
		for (Resource sourceResource : sourceResources) {
			ResourceIdentifier id = sourceResource.toIdentifier();

			Object sourceEntity = request.getEntity(id);
			if (sourceEntity != null && !(sourceEntity instanceof Resource)) {

				Object relatedEntity = null;
				if (fetchRelatedEntity) {
					relatedEntity = relationshipField.getAccessor().getValue(sourceEntity);
					if (!allowLookup && Iterable.class.isAssignableFrom(relationshipField.getType()) && relatedEntity == null) {
						// note that single-valued relations are allowed to be 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 use LookupIncludeBehavior.AUTOMATICALLY_ALWAYS");
					}
				}

				// attempt to work with full relationship and fallback to relationshipId where possible
				if (relatedEntity != null) {
					List<Resource> relatedResources =
							request.setupRelation(sourceResource, relationshipField, relatedEntity);
					loadedResources.addAll(relatedResources);
				} else if (relationshipField.hasIdField()) {
					Object relatedEntityID = relationshipField.getIdAccessor().getValue(sourceEntity);
					request.setupRelationId(sourceResource, relationshipField, relatedEntityID);
					if (fetchRelatedEntity && relatedEntityID != null && !allowLookup && mustInclude) {
						throw new IllegalStateException("inconsistent relationship '" + relationshipField.getUnderlyingName()
								+ "' for " + id + ", id "
								+ "set to " + relatedEntityID + ", but related object is null and lookup disabled");
					}
				}
			}
		}
		return loadedResources;
	}
913287
def reflect_on_all_associations klass
        klass.relationships.collect do |relationship|
          # All can be child/parent
          # ManyToMany
          # ManyToOne
          # OneToMany
          # OneToOne
          #TODO :has_and_belongs_to_many
          if relationship.kind_of?(::DataMapper::Associations::ManyToOne::Relationship) && relationship.child_model? #relationship.options[:min] == 1 && relationship.options[:max] == 1
            macro = :belongs_to
            if relationship.options[:class_name]
              # In a belongs_to, the side with the class name uses
              # the parent model, but child key for the foreign key...
              class_name = relationship.parent_model.to_s
              primary_key_name = relationship.child_key.entries.first.name
            else
              class_name = relationship.child_model.to_s
              primary_key_name = relationship.parent_key.entries.first.name
            end
          else
            macro = :has_one
            if relationship.options[:class_name]
              # but on the has_one side, it's the *child* model that
              # uses the child key for the foreign key.  Weirdness.
              class_name = relationship.child_model.to_s
              primary_key_name = relationship.child_key.entries.first.name
            else
              class_name = relationship.parent_model.to_s
              primary_key_name = relationship.parent_key.entries.first.name
            end
          end
          OpenStruct.new(
            :name => relationship.name,
            :options => {
              #:foreign_key => , # Ignore, let the calling code infer: {name}_id
              :polymorphic => false # Hard code for now
            },
            :class_name => class_name,
            :primary_key_name => primary_key_name,
            :macro => macro
          )
        end
      end
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));
                }

            }
        }

    }
706618
def relations_of(self, target, include_object=False):
        '''  '''
        if include_object:
            _ = self._execute('''
                select relations.name, ob2.code from relations, objects as ob1, objects as ob2 where relations.src=ob1.id and ob2.id=relations.dst and ob1.code=?
            ''', (self.serialize(target),))
            for i in _:
                yield i[0], self.deserialize(i[1])
        else:

            _ = self._execute('''
                select distinct relations.name from relations, objects where relations.src=objects.id and objects.code=?
            ''', (self.serialize(target),))
            for i in _:
                yield i[0]
1191502
function defineRelationshipResolution(
  schema: GraphQLSchema,
  relationships: Relationship[],
  database: DatabaseInterface,
): void {
  relationships.forEach(relationship => {
    defineFieldResolve(
      schema,
      relationship.path[0].fromType,
      relationship.fieldName,
      database.generateRelationshipResolver(relationship),
    );
  });
}
620035
def generate_endpoint_classes(db, generate_pks=False):
    """"""
    seen_classes = set()
    for cls in current_app.class_references.values():
        seen_classes.add(cls.__tablename__)
    with app.app_context():
        db.metadata.reflect(bind=db.engine)
        for name, table in db.metadata.tables.items():
            if not name in seen_classes:
                seen_classes.add(name)
                if not table.primary_key and generate_pks:
                    cls = add_pk_if_required(db, table, name)
                else:
                    cls = type(
                        str(name),
                        (sandman_model, db.Model),
                        {'__tablename__': name})
                register(cls)
515874
function (store, type, record, addId) {
    var json;
    type = this._parseModelOrType(store, type);
    json = record.serialize({includeId: true});
    if (!json.id && addId) {
      json.id = this.generateId(store, type);
    }
    type.eachRelationship(function (key, meta) {
      var records;
      if (!meta.async && meta.kind === 'hasMany' && (records = record.get(key)) && !json[key]) {
        json[key] = records.mapBy('id').filter(Boolean);
      }
    });
    return json;
  }
201058
def generate_models(args):
  """"""
  data_table = get_data_table(args.filename)
  tables = to_tables(data_table.rows_to_dicts())
  attr_indent = "\n" + args.indent * 2
  attr_sep = "," + attr_indent

  for tname, cols in tables.items():
    model_name = table_to_model_name(tname, list(cols.values())[0]["table_schema"])
    pk_cols, oth_cols = split_pks(cols)
    timestamps = get_timestamps(cols, args.created_at_col_name, args.updated_at_col_name)
    is_auto = len(pk_cols) == 1 and cols[pk_cols[0]]["is_auto"] == "t"

    attrs = OrderedDict()
    for cname in oth_cols:
      if cname not in timestamps:
        attrs[cname] = None

    print(_MODEL_SOURCE.format(
      class_name=model_name,
      base_class_name="ModelBase",
      indent=args.indent,
      table_name=repr(tname),
      pk_name=repr(pk_cols[0] if len(pk_cols) == 1 else pk_cols),
      pk_is_auto=is_auto,
      timestamps=timestamps,
      attrs="dict(" + attr_indent + attr_sep.join("{0}={1}".format(k, v) for k, v in attrs.items()) + ")"))
    print()
1284745
def related_to(self, instance):
        """"""
        return self.filter(table_name=instance.table_name, record_id=instance.record_id)
702226
def relation(self, table, origin_field, search_field,
                 destination_field=None, id_field="id"):
        
        df = self._relation(table, origin_field,
                            search_field, destination_field, id_field)
        self.df = df
204654
private void populateRelation(TaskField field, Task sourceTask, String relationship) throws MPXJException
   {
      int index = 0;
      int length = relationship.length();

      //
      // Extract the identifier
      //
      while ((index < length) && (Character.isDigit(relationship.charAt(index)) == true))
      {
         ++index;
      }

      Integer taskID;
      try
      {
         taskID = Integer.valueOf(relationship.substring(0, index));
      }

      catch (NumberFormatException ex)
      {
         throw new MPXJException(MPXJException.INVALID_FORMAT + " '" + relationship + "'");
      }

      //
      // Now find the task, so we can extract the unique ID
      //
      Task targetTask;
      if (field == TaskField.PREDECESSORS)
      {
         targetTask = m_projectFile.getTaskByID(taskID);
      }
      else
      {
         targetTask = m_projectFile.getTaskByUniqueID(taskID);
      }

      //
      // If we haven't reached the end, we next expect to find
      // SF, SS, FS, FF
      //
      RelationType type = null;
      Duration lag = null;

      if (index == length)
      {
         type = RelationType.FINISH_START;
         lag = Duration.getInstance(0, TimeUnit.DAYS);
      }
      else
      {
         if ((index + 1) == length)
         {
            throw new MPXJException(MPXJException.INVALID_FORMAT + " '" + relationship + "'");
         }

         type = RelationTypeUtility.getInstance(m_locale, relationship.substring(index, index + 2));

         index += 2;

         if (index == length)
         {
            lag = Duration.getInstance(0, TimeUnit.DAYS);
         }
         else
         {
            if (relationship.charAt(index) == '+')
            {
               ++index;
            }

            lag = DurationUtility.getInstance(relationship.substring(index), m_formats.getDurationDecimalFormat(), m_locale);
         }
      }

      if (type == null)
      {
         throw new MPXJException(MPXJException.INVALID_FORMAT + " '" + relationship + "'");
      }

      // We have seen at least one example MPX file where an invalid task ID
      // is present. We'll ignore this as the schedule is otherwise valid.
      if (targetTask != null)
      {
         Relation relation = sourceTask.addPredecessor(targetTask, type, lag);
         m_eventManager.fireRelationReadEvent(relation);
      }
   }
1181549
private static Iterable<String> getAssociationTables(EntityClass entityClass) {
        Iterable<Settable> association = filter(entityClass.getElements(),
                and(or(has(ManyToMany.class), has(ElementCollection.class)), has(JoinTable.class)));
        return transform(association, new Function<Settable, String>() {
            @Override
            public String apply(Settable input) {
                JoinTable annotation = input.getAnnotation(JoinTable.class);
                return annotation.name();
            }
        });
    }
594535
def relations():
    """"""
    rels = {}
    for reltype in relation_types():
        relids = {}
        for relid in relation_ids(reltype):
            units = {local_unit(): relation_get(unit=local_unit(), rid=relid)}
            for unit in related_units(relid):
                reldata = relation_get(unit=unit, rid=relid)
                units[unit] = reldata
            relids[relid] = units
        rels[reltype] = relids
    return rels
39170
def relationships
      r = Relationships.new
      @worksheets.each do |sheet|
        r << Relationship.new(sheet, WORKSHEET_R, WORKSHEET_PN % (r.size+1))
      end
      pivot_tables.each_with_index do |pivot_table, index|
        r << Relationship.new(pivot_table.cache_definition, PIVOT_TABLE_CACHE_DEFINITION_R, PIVOT_TABLE_CACHE_DEFINITION_PN % (index+1))
      end
      r << Relationship.new(self, STYLES_R,  STYLES_PN)
      if use_shared_strings
          r << Relationship.new(self, SHARED_STRINGS_R, SHARED_STRINGS_PN)
      end
      r
    end
382771
function Model(schema, config = {}) {
  let relationshipMap = {};
  let jsonSchema = schema.jsonSchema.withoutRefs;

  const {
    tableName,
    timestamps = false,
    validateOnInit = false,
    idColumn: idColumnInput,
    deletedAtColumn = null,
    createdAtColumn,
    updatedAtColumn,
    modelName,
    autoRestEnabled
  } = config;

  Object.keys(schema._formatted).forEach((key) => {
    if ([Types.Models, Types.Model].includes(schema._formatted[key].type)) {
      relationshipMap[key] = schema._formatted[key];
    }
  });

  const ajv = new AJV({
    allErrors: true,
    coerceTypes: true
  });

  /**
   * @prop {knex.Knex} knex A context specific knex instance
   * 
   * @class ModelInstance
   */
  return class extends Strategy {
    /**
     * Creates an instance of ModelInstance.
     * @param {object} props 
     * @memberof ModelInstance
     */
    constructor(props) {
      super();

      let validate = ajv.compile(jsonSchema);
      let result = validate(props);

      if (!result && validateOnInit) {
        throw validate.errors;
      }

      this._setProps(props);

      // default to not-persisted
      this._persisted = false;
      this._fetching = false;
      this._relationships = {};
    }

    static formatRelationship({
      relatedModel,
      foreignField,
      localField,
      type,
      through,
      throughLocalField,
      throughForeignField
    }, attr) {
      if (!relatedModel) {
        let formattedRelatedAttr = attr[0].toUpperCase() + attr.slice(1);
        relatedModel = inflect.singular(formattedRelatedAttr);
      }

      if (is(String)(relatedModel)) relatedModel = this.registry[relatedModel];

      const many = type === Types.Models;
      
      localField = localField || (many ? this.idColumn : this.guessColumnName(relatedModel.tableName, relatedModel.idColumn));

      foreignField = foreignField || (many ? this.guessColumnName(this.tableName, this.idColumn) : relatedModel.idColumn);

      if (through) {
        if (!is(String)(through)) through = this.guessTableName(this.tableName, relatedModel.tableName, true);
 
        throughLocalField = throughLocalField || this.guessColumnName(this.tableName, this.idColumn);
        throughForeignField = throughForeignField || this.guessColumnName(relatedModel.tableName, relatedModel.idColumn);
      }

      return {
        relatedModel,
        foreignField,
        localField,
        type,
        through,
        throughLocalField,
        throughForeignField,
        many
      };
    }

    static get tableName() {
      return tableName || inflect.plural(this.modelName);
    }

    get tableName() {
      return this.constructor.tableName;
    }

    static get relationshipMap() {
      return relationshipMap;
    }

    static get schema() {
      return schema;
    }

    static get autoRestEnabled() {
      return autoRestEnabled;
    }

    static get toSwagger() {
      return schema.jsonSchema.withRefs;
    }

    static get modelName() {
      return modelName || this.name;
    }

    static get idColumn() {
      return idColumnInput || this.guessIdColumn();
    }

    get idColumn() {
      return this.constructor.idColumn;
    }

    static get _softDelete() {
      return isString(deletedAtColumn);
    }
    /**
     * @param {object} registry
     * 
     * @private
     * @static
     * @memberof ModelInstance
     */
    static attachToRegistry(registry) {
      registry[this.modelName] = this;
      this.registry = registry;
    }

    /**
     * Returns a query with configuration parameters applied
     * 
     * @static
     * @returns Knex.Knex
     * @memberof ModelInstance
     */
    static getQuery() {
      let query = this.knex(this.tableName);
      if (this._softDelete) {
        query.whereNull(deletedAtColumn);
      }
      return query;
    }

    static create(props) {
      let newInstance = new this(props);
      return newInstance.save();
    }

    static async find(queryInput, {fields = '*', withRelated = []} = {}) {
      let query = this.getQuery().select(fields);
      
      if (isFunction(queryInput)) {
        queryInput(query);
      } else if (isObject(queryInput)) {
        query.where(queryInput);
      }

      let foundRows = (await query).map(row => {
        row = new this(row);
        row._persisted = true;
        return row;
      });

      for (let i = 0; i < withRelated.length; i++) {
        await this._handleWithRelated(foundRows, withRelated[i]);
      }

      return foundRows;
    }

    static async _handleWithRelated(instances, withRelated) {
      let relatedTree = withRelated.split('.').filter(val => val);

      if (instances.length > 0) {
        let [relatedAttr] = relatedTree;

        if (!relationshipMap[relatedAttr]) throw new ReferenceError('No such attribute ' + relatedAttr);
        
        let relDef = Object.assign({ instances }, this.formatRelationship(relationshipMap[relatedAttr], relatedAttr));

        let { relatedModel } = relDef;

        let results;

        if (!instances[0]._relationships[relatedAttr]) {
          results = await this._pullRelated(relDef, true);
          instances.forEach(instance => instance._relationships[relatedAttr] = results);
        } else {
          results = instances[0]._relationships[relatedAttr];
        }
        let relatedRelDef;

        Object.keys(relatedModel.relationshipMap).forEach(relName => {
          let currentRelDef = relatedModel.formatRelationship(relatedModel.relationshipMap[relName], relName);
          if (currentRelDef.foreignField === relDef.localField ||
            (
              currentRelDef.through && relDef.through &&
              currentRelDef.through === relDef.through &&
              currentRelDef.throughForeignField === relDef.throughLocalField &&
              currentRelDef.throughLocalField === relDef.throughForeignField
            )
            ) {
            relatedRelDef = Object.assign({ relName }, currentRelDef);
          }
        });

        instances.forEach(instance => {
          instance[relatedAttr] = results.map[instance[relDef.localField]];
          if (!instance[relatedAttr] && (relDef.type === Types.Models)) {
            instance[relatedAttr] = [];
          }
          if (relatedRelDef) {
            results.array.forEach(result => {
              if (!relatedRelDef.through && (result[relatedRelDef.localField] === instance[relDef.localField])) {
                if (relatedRelDef.type === Types.Models) {
                  (result[relatedRelDef.relName] = result[relatedRelDef.relName] || []).push(instance);
                  result;
                } else {
                  result[relatedRelDef.relName] = instance;
                }
              }
            });
          }
        });
        if (relatedTree.length > 1) {
          await relatedModel._handleWithRelated(results.array, relatedTree.slice(1).join('.'));
        }
      } else {
        return instances;
      }
    }

    static async findById(id, {fields = '*', withRelated = []} = {}) {
      let [props] = await this.getQuery().where(this.idColumn, id).select(fields);
      if (props) {
        let foundRecord = new this(props);
        for (let i = 0; i < withRelated.length; i++) {
          await this._handleWithRelated([foundRecord], withRelated[i]);
        }
        foundRecord._persisted = true;
        return foundRecord;
      } else {
        return null;
      }
    }

    static update(query, updates) {
      let updateQuery = this.getQuery();
      if (isFunction(query)) {
        query(updateQuery);
      } else {
        updateQuery.where(query);
      }

      return updateQuery.update(updates, '*');
    }

    static async restore(id) {
      if (!this._softDelete) {
        throw new ReferenceError(this.modelName + ' does not support soft deletes');
      }
      await this.knex(this.tableName)
        .where(this.idColumn, id)
        .update(deletedAtColumn, null);
    }

    static async remove(queryInput) {
      let results = await this.find(queryInput);
      return Promise.all(results.map(async result => result.destroy()));
    }

    get changes() {
      return clone(this._changes);
    }

    get knex() {
      return this.constructor.knex;
    }

    get query() {
      return this.constructor.getQuery();
    }

    async save(options = defaultSaveOptions) {

      if (options.validate && !this.validate()) {
        throw this.errors;
      }

      if (timestamps) {
        if (!this._persisted) {
          this._props[createdAtColumn || this.constructor.guessColumnName('created', 'at')] = new Date();
        }

        this._props[updatedAtColumn || this.constructor.guessColumnName('updated', 'at')] = new Date();
      }

      if (this._persisted) {
        await this.knex(this.tableName)
          .where(this.idColumn, this[this.idColumn])
          .update(this._changes);

      } else {
        let results = await this.knex(this.tableName).insert(this._props).returning('id');
        this._props[this.idColumn] = results[0];
        this._persisted = true;
      }
      this._setProps(this._props);
      return this;
    }

    reset() {
      this._setProps(this._original);
    }

    destroy() {
      let deleteQuery = this.query
        .where(this.idColumn, this[this.idColumn]);
      if (this.constructor._softDelete) {
        return deleteQuery.update(deletedAtColumn, new Date);
      } else {
        return deleteQuery.del();
      }
    }

    _setProps(props) {
      this._original = clone(props);
      this._props = props;
      this._changes = {};

      for (let key in props) {
        this.__defineGetter__(key, () => this._props[key]);
        this.__defineSetter__(key, (value) => {
          this._props[key] = value;

          this._changes[key] = value;
        });
      }
    }

    toJSON(ignoredRecord) {
      let relMap = Object.keys(relationshipMap).reduce((map, relName) => {
        if (this[relName] && (this[relName] !== ignoredRecord)) {
          map[relName] = is(Array)(this[relName]) ?
            this[relName].filter(rec => rec !== ignoredRecord).map(rec => rec.toJSON(this)) :
            this[relName].toJSON(this);
        }
        return map;
      }, {});
      return Object.assign(relMap, this._props);
    }

    validate() {
      let valid = ajv.validate(jsonSchema, this);
      this.errors = ajv.errors;
      return valid;
    }

    async pullRelated(key) {
      let relDef = relationshipMap[key.tableName || key];
      if (relDef) {
        relDef = this.constructor.formatRelationship(relDef, key);
        return this[key] = (await this.constructor._pullRelated(Object.assign({ instances: this }, relDef))).array;
      } else {
        throw new ReferenceError('No such relationship: ' + key);
      }
    }

    static async _pullRelated(relDef) {
      const {
        relatedModel,
        foreignField,
        localField,
        through,
        throughLocalField,
        throughForeignField,
        many
      } = this.formatRelationship(relDef);
      const { instances } = relDef;
      let relatedValue = is(Array)(instances) ? pluck(localField)(instances) : [instances[localField]];

      let relatedQuery;

      switch (relatedValue.length) {
      case 1:
        relatedQuery = query => {
          query.where(foreignField, relatedValue[0]);
          return query;
        };
        break;
      default:
        relatedQuery = query => {
          query.whereIn(foreignField, relatedValue);
          return query;
        };
      }

      if (through) {
        relatedQuery = query => {
          query.join(through, `${relatedModel.tableName}.${relatedModel.idColumn}`, `${through}.${throughForeignField}`);

          query.whereIn(`${throughLocalField}`, relatedValue);

          return query;
        };
      }

      let results = await relatedModel.find(relatedQuery, {}, true);

      let map = {};
      results.forEach(result => {
        const mapKey = through ? result[throughLocalField] : result[foreignField];
        if (many) {
          (map[mapKey] = map[mapKey] || []).push(result);
        } else {
          map[mapKey] = result;
        }
      });
      return {map, array: results};
    }
  };
}
967516
def extend_relations(self, data, kind):
        
        # 'data' is a generator object. It can throw an exception while being
        # consumed. This could happen if the user has launched the app without
        # specifying a database name. This exception must be handled to prevent
        # crashing.
        try:
            data = [self.escaped_names(d) for d in data]
        except Exception:
            data = []

        # dbmetadata['tables'][$schema_name][$table_name] should be a list of
        # column names. Default to an asterisk
        metadata = self.dbmetadata[kind]
        for relname in data:
            try:
                metadata[self.dbname][relname[0]] = ['*']
            except KeyError:
                _logger.error('%r %r listed in unrecognized schema %r',
                              kind, relname[0], self.dbname)
            self.all_completions.add(relname[0])