if relation is not None, when fetch manytomany result, also
        fetch relation record and saved them to manytomany object,
        and named them as relation.
        
        If relation_name is not given, then default value is 'relation'
547583
def with_relation(self, relation_name=None):
        
        if not relation_name:
            relation_name = 'relation'
        if hasattr(self.modelb, relation_name):
            raise Error("The attribute name %s has already existed in Model %s!" % (relation_name, self.modelb.__name__))
        if not self.through_model:
            raise Error("Only with through style in ManyToMany supports with_relation function of Model %s!" % self.modelb.__name__)
        self.with_relation_name = relation_name
        return self
1066035
def related_records2marc(self, key, value):
    
    if value.get('relation_freetext'):
        return {
            'i': value.get('relation_freetext'),
            'w': get_recid_from_ref(value.get('record')),
        }
    elif value.get('relation') == 'successor':
        self.setdefault('78502', []).append({
            'i': 'superseded by',
            'w': get_recid_from_ref(value.get('record')),
        })
    elif value.get('relation') == 'predecessor':
        self.setdefault('78002', []).append({
            'i': 'supersedes',
            'w': get_recid_from_ref(value.get('record')),
        })
    else:
        raise NotImplementedError(u"Unhandled relation in related_records: {}".format(value.get('relation')))
1370871
function(name, options) {
    const self = this
    const utils = self.store.utils

    // called every time before a parent query occures, with an include of this relation.
    // maybee the conditions of the parent query will contain variables whilch will let us
    // query this relation simultaneously.
    // e.g. Parent.find(99).include('children')
    //      with from: 'id' to: 'parent_id'
    //      99 => is the id!
    options.loadFromConditions =
      options.loadFromConditions ||
      function(parentCollection, parentConditions, include) {
        include = include || {}
        const conditions = utils.parentConditionsToConditions(
          parentConditions || [],
          options.from,
          options.to
        )
        if (!conditions) return

        return defaultFetch(parentCollection, conditions, include)
      }

    // called every time we need to fetch data for that relation
    options.loadFromRecords =
      options.loadFromRecords ||
      function(parentCollection, include, existingCollection) {
        include = include || {}

        const conditions = utils.recordsToConditions(
          parentCollection,
          options.from,
          options.to
        )
        if (!conditions) return Promise.resolve([]) // not enough info to form conditions. Better return an empty result instead of loading the whole dataset!

        return defaultFetch(
          parentCollection,
          conditions,
          include,
          existingCollection
        ).then(function(result) {
          // add the result to corresponding record
          parentCollection.forEach(function(record) {
            record.relations[name] = options.filterCache(record, result)
          })

          return result
        })
      }

    function defaultFetch(
      parentCollection,
      conditions,
      include,
      existingCollection
    ) {
      const relationCache = parentCollection.getInternal('relation_cache') || {}

      // return cached result, if available!
      if (relationCache[options.name]) {
        const result = relationCache[options.name]
        if (!result.then) return Promise.resolve(relationCache[options.name])
        return result
      }

      const query = options.model.where(conditions)
      if (options.conditions) query.where(options.conditions) // conditions on the relation
      if (options.scope) query[options.scope].apply(query, include.args) // scope on the relation
      if (include.conditions) query.where(include.conditions) // nested conditions via `where({relation_name: {...conditions...}})`
      if (include.children) query.include(include.children) // nested includes via `include({relation_name: {nested_relation_name: { ... }}})`
      if (include.scope) query[include.scope].apply(query, include.args) // scope defined via `include({relation_name: {$scope: 'myscope'}})`
      if (existingCollection) {
        const existingConditions = existingCollection.getInternal('conditions')
        const existingIncludes = existingCollection.getInternal('includes')

        if (existingIncludes) query.addInternal('includes', existingIncludes)
        if (existingConditions) {
          // add only new conditions
          const intConditions = query.getInternal('conditions')
          query.addInternal(
            'conditions',
            existingConditions.filter(function(c) {
              if (options.to.indexOf(c.attribute) !== -1) return false // ignore conditions with the target id field. existinCollection will automatically add such an id.

              var match = false
              intConditions.forEach(function(intC) {
                if (options.model.store.utils.compareObjects(c, intC, true))
                  match = true
              })
              return !match
            })
          )
        }

        utils.assignInternals(query, existingCollection, {
          exclude: ['relation', 'relation_to']
        })
      }

      const promise = query.then(function(result) {
        // overwrite cache result
        relationCache[options.name] = result
        return result
      })

      // store the promise in the cache object
      relationCache[options.name] = promise
      parentCollection.setInternal('relation_cache', relationCache)

      return promise
    }

    // called with every parent and child record. returns true/false for matching relations
    options.filterCache =
      options.filterCache ||
      function(parentRecord, records) {
        if (options.model) {
          const chain = options.model.chain()

          if (records) {
            if (!Array.isArray(records)) records = [records]
            const relatedRecords = records.filter(function(record) {
              var match = true

              options.from.forEach(function(key, index) {
                const opposite = options.to[index]
                const val1 = parentRecord[key]
                const val2 = record[opposite]
                if (!utils.checkFieldEquality(val1, val2)) match = false
              })
              return match
            })

            chain.add(relatedRecords) // add all child records
            chain._exists() // set this collection as existing (all records fetched from the datastore!)
          }

          chain.setInternal('relation', options) // add the parent relation of this collection
          chain.setInternal('relation_to', parentRecord) // + the parent record

          return chain
        }

        throw new Error('You need to implement your own `filterCache` function!')
      }

    options.getFromCache = function(parentRecord, include, existingCollection) {
      const parentCollection =
        parentRecord.__chainedModel ||
        parentRecord.model.chain().add(parentRecord)

      return options
        .loadFromRecords(parentCollection, include || {}, existingCollection)
        .then(function(result) {
          if (!result) return null
          return options.filterCache(parentRecord, result)
        })
    }

    return options
  }
932409
function relation (relatedModelName) {
    // if related model is not linked then lookup through immutable module
    if (!this.relations[relatedModelName] || !this.relations[relatedModelName].model) {
        // module name has Model appended
        var relatedModuleName = relatedModelName + 'Model'
        // check that module exists
        assert.ok(immutable.hasModule(relatedModuleName), 'module not found for relation '+relatedModelName)
        // get module
        var module = immutable.module(relatedModuleName)
        // get module meta data to get model
        var meta = module.meta
        // module must be ImmutableCoreModel
        assert.ok(meta.class === 'ImmutableCoreModel', 'invalid model for relation '+relatedModelName)
        // get model
        var relatedModel = meta.instance
        // if entry does not exist in relations create one
        if (!this.relations[relatedModelName]) {
            // require related model to have a relation to this model
            assert.ok(relatedModel.relations[this.name], 'no relation for '+relatedModelName)
            // build local relation from other model
            var relation = this.relations[relatedModelName] = _.cloneDeep(relatedModel.relations[this.name])
        }
        else {
            var relation = this.relations[relatedModelName]
        }
        // set model for relation
        relation.model = relatedModel
        // if relation has via and via model is not loaded then load it
        if (relation.via && !relation.viaModel) {
            // get via model module name
            var viaModuleName = relation.via+'Model'
            // check that module exists
            assert.ok(immutable.hasModule(viaModuleName), 'module not found for relation via '+relation.via)
            // get module
            var module = immutable.module(viaModuleName)
            // get module meta data to get model
            var meta = module.meta
            // module must be ImmutableCoreModel
            assert.ok(meta.class === 'ImmutableCoreModel', 'invalid model for relation via '+relation.via)
            // store model for relation via
            relation.viaModel = meta.instance
        }
        // set column names for via relation
        if (relation.via) {
            // get id column for model
            var idColumn = this.columnName('id')
            var originalIdColumn = this.columnName('originalId')
            // original id is on via table directly
            if (relation.viaModel.columns[originalIdColumn]) {
                relation.modelIdColumn = originalIdColumn
                relation.viaModelIdColumn = originalIdColumn
            }
            // original id is linked to via table on default column
            else if (relation.viaModel.columnName(originalIdColumn)) {
                relation.modelIdColumn = originalIdColumn
                relation.viaModelIdColumn = relation.viaModel.columnName(originalIdColumn)
            }
            // id column is on via table directly
            else if (relation.viaModel.columns[idColumn]) {
                relation.modelIdColumn = idColumn
                relation.viaModelIdColumn = idColumn
            }
            // id column is linked to via table on default column
            else if (relation.viaModel.columnName(idColumn)) {
                relation.modelIdColumn = idColumn
                relation.viaModelIdColumn = relation.viaModel.columnName(idColumn)
            }
            // error
            else {
                throw new Error('invalid id column for model '+this.name+' relation '+relatedModelName)
            }
            // get id column for relation model that links it to via model
            var relationIdColumn = relation.model.columnName('id')
            var relationOriginalIdColumn = relation.model.columnName('originalId')
            // relation original id is on via table directly
            if (relation.viaModel.columns[relationOriginalIdColumn]) {
                relation.relationIdColumn = relationOriginalIdColumn
                relation.viaRelationIdColumn = relationOriginalIdColumn
            }
            // relation original id is linked to via table on default column
            else if (relation.viaModel.columnName(relationOriginalIdColumn)) {
                relation.relationIdColumn = relationOriginalIdColumn
                relation.viaRelationIdColumn = relation.viaModel.columnName(relationOriginalIdColumn)
            }
            // relation id is on via table directly
            else if (relation.viaModel.columns[relationIdColumn]) {
                relation.relationIdColumn = relationIdColumn
                relation.viaRelationIdColumn = relationIdColumn
            }
            // relation id is linked to via table on default column
            else if (relation.viaModel.columnName(relationIdColumn)) {
                relation.relationIdColumn = relationIdColumn
                relation.viaRelationIdColumn = relation.viaModel.columnName(relationIdColumn)
            }
            // error
            else {
                throw new Error('invalid id column for model '+this.name+' relation '+relatedModelName)
            }
        }
        // set column names for direct relation
        else {
            // get id column for related model - direct relation can go either
            // way so need to test all possibilities
            var modelIdColumn = this.columnName('id')
            var modelOriginalIdColumn = this.columnName('originalId')
            var relationIdColumn = relation.model.columnName('id')
            var relationOriginalIdColumn = relation.model.columnName('originalId')
            // original id links directly to relation
            if (relation.model.columns[modelOriginalIdColumn]) {
                relation.modelIdColumn = modelOriginalIdColumn
                relation.relationIdColumn = modelOriginalIdColumn
            }
            // original id links to relation on default column
            else if (relation.model.columnName(modelOriginalIdColumn)) {
                relation.modelIdColumn = modelOriginalIdColumn
                relation.relationIdColumn = relation.model.columnName(modelOriginalIdColumn)
            }
            // id links directly to relation
            else if (relation.model.columns[modelIdColumn]) {
                relation.modelIdColumn = modelIdColumn
                relation.relationIdColumn = modelIdColumn
            }
            // id links to relation on default column
            else if (relation.model.columnName(modelIdColumn)) {
                relation.modelIdColumn = modelIdColumn
                relation.relationIdColumn = relation.model.columnName(modelIdColumn)
            }
            // relation original id links directly to model
            else if (this.columns[relationOriginalIdColumn]) {
                relation.modelIdColumn = relationOriginalIdColumn
                relation.relationIdColumn = relationOriginalIdColumn
            }
            // relation original id links to model on default column
            else if (this.columnName(relationOriginalIdColumn)) {
                relation.modelIdColumn = this.columnName(relationOriginalIdColumn)
                relation.relationIdColumn = relationOriginalIdColumn
            }
            // relation id links directly to model
            else if (this.columns[relationIdColumn]) {
                relation.modelIdColumn = relationIdColumn
                relation.relationIdColumn = relationIdColumn
            }
            // relation id links to model on default column
            else if (this.columnName(relationIdColumn)) {
                relation.modelIdColumn = this.columnName(relationIdColumn)
                relation.relationIdColumn = relationIdColumn
            }
            // error
            else {
                throw new Error('invalid id column for model '+this.name+' relation '+relatedModelName)
            }
        }
    }
    // return relation
    return this.relations[relatedModelName]
}
45568
function(records) {
    var self = this.chain()
    var relation = self.getInternal('relation')
    var parentRecord = self.getInternal('relation_to')

    if (!records) return self
    if (!Array.isArray(records)) records = [records]

    // build a map to check if existing records were added - via primary key
    const primaryKeys = self.definition.primaryKeys
    const map = {}
    self.forEach(function(record) {
      var mapKey = []
      primaryKeys.forEach(function(key) {
        if (record[key]) mapKey.push(record[key])
      })
      if (mapKey.length > 0) map[mapKey.join('|')] = record
    })

    records.forEach(function(record) {
      var fromKeys = false
      var mapKey = []

      if (record) {
        // check if `records` is a primitive, or an array of primitives with the same amount of elements as our primary keys
        if (
          typeof record !== 'object' ||
          (Array.isArray(record) &&
            record.length === primaryKeys.length &&
            typeof record[0] !== 'object')
        ) {
          // not a record/object... so it must be a primary key!
          if (self.options.polymorph)
            throw new Error('Polymorphic relations need to add a record!')

          var keys = record
          const tmpRecord = {}

          if (!Array.isArray(keys)) keys = [keys]

          primaryKeys.forEach(function(key, index) {
            if (keys[index]) {
              tmpRecord[key] = keys[index]
              mapKey.push(keys[index])
            }
          })

          if (mapKey.length > 0 && map[mapKey.join('|')]) {
            // found a record no update needed, because we only got the id...
            return
          }

          record = tmpRecord
          fromKeys = true
        }

        primaryKeys.forEach(function(key) {
          if (record[key]) mapKey.push(record[key])
        })

        if (mapKey.length > 0 && map[mapKey.join('|')]) {
          // found a record for update!
          map[mapKey.join('|')].set(record)
          return
        }

        const originalInput = record
        // convert object to a record
        if (self.options.polymorph) {
          if (record.model && !(record instanceof record.model))
            throw new Error(
              'Record/Model instance expected in polymorphic relation!'
            )
        } else {
          if (!(record instanceof self.model)) record = self.model.new(record)
        }

        record.__chainedModel = self

        if (fromKeys) {
          record._exists()
        } else {
          if (mapKey.length > 0 && mapKey.length === primaryKeys.length) {
            record._exists()
            if (!(originalInput instanceof self.model)) {
              // set changes. if for example the record is not loaded, but we now have the primary keys. Only the given fields are changes.
              // all fields that are not present in the original input, must not be changed, because we dont now their value.
              Object.keys(originalInput).forEach(function(key) {
                // ignore primary keys
                if (primaryKeys.indexOf(key) === -1) {
                  record.changes[key] = [undefined, originalInput[key]]
                }
              })
            }
          }
        }

        // a new one
        self.push(record)

        if (relation && parentRecord) {
          if (record && typeof relation.add === 'function') {
            relation.add.call(self, parentRecord, record)
          }
        }
      }
    })

    return self
  }
513410
public function afterSave()
    {
        if ($this->_relationsSaveStarted === false) {
            /** @var BaseActiveRecord $owner */
            $owner = $this->owner;
            $this->_relationsSaveStarted = true;
            // Populate relations with updated values
            foreach ($this->_newRelationValue as $name => $value) {
                $owner->populateRelation($name, $value);
            }
            try {
                foreach ($this->_relations as $relationName) {
                    if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing...
                        Yii::debug("Linking {$relationName} relation", __METHOD__);
                        /** @var ActiveQuery $relation */
                        $relation = $owner->getRelation($relationName);
                        if ($relation->multiple === true) { // Has many relation
                            $this->_afterSaveHasManyRelation($relationName);
                        } else { // Has one relation
                            $this->_afterSaveHasOneRelation($relationName);
                        }
                        unset($this->_oldRelationValue[$relationName]);
                    }
                }
            } catch (Exception $e) {
                Yii::warning(get_class($e) . ' was thrown while saving related records during afterSave event: ' . $e->getMessage(), __METHOD__);
                $this->_rollback();
                /***
                 * Sadly mandatory because the error occurred during afterSave event
                 * and we don't want the user/developper not to be aware of the issue.
                 ***/
                throw $e;
            }
            $owner->refresh();
            $this->_relationsSaveStarted = false;
        }
    }
669595
function makerelation (model, relation) {
	let options = {
		as: relation.As,
		foreignKey: relation.key
	};
	let target = exp.databases[inflector.pluralize(relation.Children)];
	if (relation.Rel !== 'manyToMany') {
		exp.databases[model][relation.Rel](target, options);
	} else {
		exp.databases[model].prototype.many2many = exp.databases[model].prototype.many2many || {};
		exp.databases[model].prototype.many2many[relation.Parent] = function (id, id2) {
			if (id && id2) {
				return exp.databases[relation.Children].findcre({
					[`${model}ID`]: id,
					[`${relation.Parent}ID`]: id2
				});
			}
			return exp.databases[relation.Children].find({
				where: {
					[`${model}ID`]: id
				}
			}).then(records => {
				let all = [];
				for (const record of records) {
					all.push(exp.databases[relation.Parent].findById(record[`${relation.Parent}ID`]));
				}
				return Promise.all(all);
			});
		};
	}
}
1105512
function executeRelatedResultWithQuery (result, relatedName) {
    // get custom args for related model query
    var relatedArgs = this.args.with[relatedName]
    // get relation
    var relation = this.model.relation(relatedName)
    // build query args
    var queryArgs = {
        all: true,
        allow: this.args.allow,
        session: this.session,
        where: { relation: { name: this.model.name } },
    }
    // relation is via a linking table
    if (relation.via) {
        queryArgs.where.relation[relation.viaModelIdColumn] = result[relation.modelIdColumn] || result[model.defaultColumns[relation.modelIdColumn]]
    }
    // relation is direct
    else {
        queryArgs.where.relation[relation.relationIdColumn] = result[relation.modelIdColumn] || result[model.defaultColumns[relation.modelIdColumn]]
    }
    // merge args
    if (typeof relatedArgs === 'object') {
        _.merge(queryArgs, relatedArgs)
    }
    // do query on related model
    return relation.model.query(queryArgs)
    // merge related records once loaded
    .then(results => {
        result._related[relatedName] = results
    })
}
383051
def start_transfer(self, relation_name):
    
    self.reset(relation_name)
    relation = Relation(name=relation_name)
    self.data_access.insert_model(relation)
    return relation
833592
def related_results(self):
        
        return bind_api(
            api=self,
            path='/related_results/show/{id}.json',
            payload_type='relation', payload_list=True,
            allowed_param=['id'],
            require_auth=False
        )
1324048
def get_relation_kwargs(field_name, relation_info):
    
    model_field, related_model, to_many, to_field, has_through_model = relation_info
    kwargs = {
        'queryset': related_model._default_manager,
        'view_name': get_detail_view_name(related_model)
    }

    if to_many:
        kwargs['many'] = True

    if to_field:
        kwargs['to_field'] = to_field

    if has_through_model:
        kwargs['read_only'] = True
        kwargs.pop('queryset', None)

    if model_field:
        if model_field.verbose_name and needs_label(model_field, field_name):
            kwargs['label'] = capfirst(model_field.verbose_name)
        help_text = model_field.help_text
        if help_text:
            kwargs['help_text'] = help_text
        if not model_field.editable:
            kwargs['read_only'] = True
            kwargs.pop('queryset', None)
        if kwargs.get('read_only', False):
            # If this field is read-only, then return early.
            # No further keyword arguments are valid.
            return kwargs

        if model_field.has_default() or model_field.blank or model_field.null:
            kwargs['required'] = False
        if model_field.null:
            kwargs['allow_null'] = True
        if model_field.validators:
            kwargs['validators'] = model_field.validators
        if getattr(model_field, 'unique', False):
            validator = UniqueValidator(queryset=model_field.model._default_manager)
            kwargs['validators'] = kwargs.get('validators', []) + [validator]
        if to_many and not model_field.blank:
            kwargs['allow_empty'] = False

    return kwargs
924133
def get_from_relations(self, query,aliases):
        '''
        
        '''
        return [aliases[rel.get_name()] for rel in query.get_relations() if not rel.is_negated()]
995274
private void onRelationalAttributes(List<RelationHolder> rlHolders, Row row, Table schemaTable)
    {
        // Iterate over relations
        if (rlHolders != null && !rlHolders.isEmpty())
        {
            for (RelationHolder rh : rlHolders)
            {
                String relationName = rh.getRelationName();
                Object valueObj = rh.getRelationValue();

                if (!StringUtils.isEmpty(relationName) && valueObj != null)
                {
                    if (valueObj != null)
                    {
                        NoSqlDBUtils.add(schemaTable.getField(relationName), row, valueObj, relationName);
                        KunderaCoreUtils.printQuery(
                                "Add relation: relation name:" + relationName + "relation value:" + valueObj,
                                showQuery);
                    }
                }
            }
        }
    }
631457
def _assert_relation_does_not_exists(self):
        
        relations = self.database._relations[self.related_to]
        existing = [r for r in relations if r[2] == self.related_name]
        if existing:
            error = ("The related name defined for the field '%s.%s', named '%s', already exists "
                     "on the model '%s' (tied to the field '%s.%s')")
            raise ImplementationError(error % (self._model.__name__, self.name, self.related_name,
                                      self.related_to, existing[0][1], existing[0][0]))
917596
def init_relation(self, models, relation):
        
        for model in models:
            model.set_relation(relation, Result(None, self, model))

        return models
1038836
public function getEmptyValueForRelationship(string $relation)
    {
        if ($this->isSingleRelationship($relation)) {
            return;
        }

        if ($this->isManyRelationship($relation)) {
            return new Collection();
        }

        throw new MappingException("Cannot determine default value of $relation");
    }
101800
def collect_consequences(self):
        
        consequences = {self.key()}
        for relation in self.referenced_by.values():
            consequences.update(relation.collect_consequences())
        return consequences