Initialize Relations present in this.relations; determine the type (HasOne/HasMany), then creates a new instance.
Invoked in the first call so 'set' (which is made from the Backbone.Model constructor).
173040
function() {
			this.acquire(); // Setting up relations often also involve calls to 'set', and we only want to enter this function once
			this._relations = [];
			
			_.each( this.relations, function( rel ) {
					var type = !_.isString( rel.type ) ? rel.type :	Backbone[ rel.type ] || Backbone.Relational.store.getObjectByName( rel.type );
					if ( type && type.prototype instanceof Backbone.Relation ) {
						new type( this, rel ); // Also pushes the new Relation into _relations
					}
					else {
						Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid type!', rel );
					}
				}, this );
			
			this._isInitialized = true;
			this.release();
			this.processQueue();
		}
28501
public function setRelated($value)
    {
        $this->loadData(true);

        if (is_null($value)) {
            $value = [];
        }

        if (!is_array($value)) {
            throw new RelationException("HasMany relation can only be set with array of entities");
        }

        //Do not add items twice
        $matched = [];
        foreach ($value as $index => $record) {
            if (is_null($record)) {
                unset($value[$index]);
                continue;
            }

            $this->assertValid($record);
            if (!empty($instance = $this->matchOne($record))) {
                $matched[] = $instance;
                unset($value[$index]);
            }
        }

        //Unlink records
        foreach (array_diff($this->instances, $matched) as $record) {
            $this->unlink($record);
        }

        //Add new record
        foreach ($value as $record) {
            $this->link($record);
        }
    }
287269
def create(self):
        
        # Calls each of these methods in order.  _populate_from_lines and
        # _update_relations must be implemented in subclasses.
        self._init_tables()
        self._populate_from_lines(self.iterator)
        self._update_relations()
        self._finalize()
901
function( key, options ) {
			options || ( options = {} );
			var rel = this.getRelation( key ),
				keyContents = rel && rel.keyContents,
				toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) {
						var id = _.isString( item ) || _.isNumber( item ) ? item : item[ rel.relatedModel.prototype.idAttribute ];
						return id && !Backbone.Relational.store.find( rel.relatedModel, id );
					}, this );
			
			if ( toFetch && toFetch.length ) {
				// Create a model for each entry in 'keyContents' that is to be fetched
				var models = _.map( toFetch, function( item ) {
						if ( typeof( item ) === 'object' ) {
							var model = new rel.relatedModel( item );
						}
						else {
							var attrs = {};
							attrs[ rel.relatedModel.prototype.idAttribute ] = item;
							var model = new rel.relatedModel( attrs );
						}
						return model;
					}, this );
				
				// Try if the 'collection' can provide a url to fetch a set of models in one request.
				if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) {
					var setUrl = rel.related.url( models );
				}
				
				// An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls.
				// To make sure it can, test if the url we got by supplying a list of models to fetch is different from
				// the one supplied for the default fetch action (without args to 'url').
				if ( setUrl && setUrl !== rel.related.url() ) {
					var opts = _.defaults( {
							error: function() {
									var args = arguments;
									_.each( models, function( model ) {
											model.destroy();
											options.error && options.error.apply( model, args );
										})
								},
							url: setUrl
						},
						options,
						{ add: true }
					);
					
					var requests = [ rel.related.fetch( opts ) ];
				}
				else {
					var requests = _.map( models, function( model ) {
							var opts = _.defaults( {
								error: function() {
										model.destroy();
										options.error && options.error.apply( model, arguments );
									}
								},
								options
							);
							return model.fetch( opts );
						}, this );
				}
			}
			
			return _.isUndefined( requests ) ? [] : requests;
		}
457820
def initialize_post(self):
        
        self.model = self.get_model()
        for key in self.model.keys():
            self.model.set(key, self.json_arguments.get(key))
917596
def init_relation(self, models, relation):
        
        for model in models:
            model.set_relation(relation, Result(None, self, model))

        return models
597096
function Model(collectionName, attributes, values) {
    this.collectionName = collectionName;
    this.idAttribute = Model.getId(attributes);
    this.attributes = attributeValidator.validate(attributes);
    this.values = { };
    this.virtuals = { };

    // initially add the null value from all attributes
    for (var key in this.attributes) {
        this.values[key] = undefined;
    }

    // prevents from modifying values and adding properties
    Object.freeze(this.attributes);

    // prevents from adding new properties
    Object.seal(this.values);

    // sets the initial values
    this.set(values);
}
324642
def init_model(self, model, value):
        
        if value is None and self.default is not None:
            value = self.default() if callable(self.default) else self.default

        self.set_value(model, value)
245177
function Set() {
            var set = this;
            set = emulateES6construct(set);
            if (!set._es6set) {
              throw new TypeError('bad set');
            }

            defineProperties(set, {
              '[[SetData]]': null,
              '_storage': emptyObject()
            });

            // Optionally initialize map from iterable
            var iterable = arguments[0];
            if (iterable !== undefined && iterable !== null) {
              var it = ES.GetIterator(iterable);
              var adder = set.add;
              if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); }
              while (true) {
                var next = ES.IteratorNext(it);
                if (next.done) { break; }
                var nextItem = next.value;
                adder.call(set, nextItem);
              }
            }
            return set;
          }
361438
function(model, options) {
            options || (options = {});
            if (!(model instanceof Model)) {
                var attrs = model;
                options.collection = this;
                model = new this.model(options, attrs);
            } else if (!model.collection) {
                model.collection = this;
            }
            return model;
        }
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
  }
1272501
private function initRelations() {
    if ($this->relations == null) {
      $this->relations = [];
      $this->relations['all'] = array_values($this->getRelationDescriptions());
      $this->relations['parent'] = [];
      $this->relations['child'] = [];
      $this->relations['undefined'] = [];
      $this->relations['nm'] = [];

      foreach ($this->relations['all'] as $relation) {
        $hierarchyType = $relation->getHierarchyType();
        $hierarchyKey = $hierarchyType == 'parent' || $hierarchyType == 'child' ?
                $hierarchyType : 'undefined';
        $this->relations[$hierarchyKey][] = $relation;

        // also store relations to many to many objects, because
        // they would be invisible otherwise
        if ($relation instanceof RDBManyToManyRelationDescription) {
          $nmRelation = $relation->getThisEndRelation();
          $this->relations['nm'][$nmRelation->getOtherRole()] = $nmRelation;
        }
      }
    }
  }
939801
def first_or_new(self, _attributes=None, **attributes):
        
        if _attributes is not None:
            attributes.update(_attributes)

        instance = self.where(attributes).first()

        if instance is None:
            instance = self._related.new_instance()
            instance.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())

        return instance
98866
function init (model) {
    if (model.__ttl) return;

    var distinct_ = model.distinct;
    model.distinct = function distinct (field, cond, cb) {
      applyTTL(cond);
      return distinct_.call(model, field, cond, cb);
    }

    'findOne find count'.split(' ').forEach(function (method) {
      var fn = model[method];

      model[method] = function (cond, fields, opts, cb) {
        if (!cond) {
          cond = {};
        } else if ('function' == typeof cond) {
          cb = cond;
          cond = {};
        }

        applyTTL(cond);
        return fn.call(model, cond, fields, opts, cb);
      }
    });

    'where $where'.split(' ').forEach(function (method) {
      var fn = model[method];
      model[method] = function () {
        var query = fn.apply(this, arguments)
          , cond = {};
        applyTTL(cond);
        return query.find(cond);
      }
    });

    if (reap) {
      model.startTTLReaper();
    }
  }
942930
public function setRelated($value)
    {
        $this->loadData(true);

        if (is_null($value)) {
            $value = [];
        }

        if (!is_array($value)) {
            throw new RelationException("HasMany relation can only be set with array of entities");
        }

        //Do not add items twice
        $matched = [];
        foreach ($value as $index => $item) {
            if (is_null($item)) {
                unset($value[$index]);
                continue;
            }

            $this->assertValid($item);
            if (!empty($instance = $this->matchOne($item))) {
                $matched[] = $instance;
                unset($value[$index]);
            }
        }

        $this->deleteInstances = array_diff($this->instances, $matched);
        $this->instances = $matched + $value;
    }
136040
function(name, options) {
    const self = this
    const utils = this.store.utils

    options.preInitialize = function() {
      options.relation = options.relation || name
      options.from = []
      options.to = []

      if (!Array.isArray(options.through)) options.through = [options.through]

      // add the last relation name for easier looping
      options.through.push(options.relation)

      var tmpDefinition = self
      var targetRelation
      var relation

      // find the last relation of the through list
      for (var index = 0; index < options.through.length; index++) {
        const relationName = options.through[index]

        if (!tmpDefinition)
          throw new Error(
            "Can't create a `through` relation through a `has` or `belongs_to_polymorphic` relation'"
          )

        relation = tmpDefinition.relations[relationName]
        if (!relation)
          throw new Error(
            "Can't find relation '" +
              relationName +
              "' on model " +
              tmpDefinition.modelName
          )
        if (relation === options) throw new Error('Relation loop detected!')
        if (relation.type === 'has')
          throw new Error(
            "Can't create a `through` relation through a `has` relation'"
          )

        relation.init()

        // in case we have a nested through relation
        if (relation.through) {
          options.through.splice.apply(
            options.through,
            [index, 1].concat(relation.through)
          )
          index += relation.through.length - 1
        }

        targetRelation = relation
        if (relation.model) tmpDefinition = relation.model.definition
      }

      options.targetRelation = targetRelation
      if (relation.model) options.model = relation.model
    }

    options.rawGetter = function() {
      var result = this.relations[name]

      if (result === undefined) {
        if (this['_' + options.through[0]] === undefined) return // through relation is not loaded, so we can't filter it

        result = options.filterCache(this)
        options.setResult(this, result)
      }

      if (typeof options.transform === 'function') {
        return options.transform(result)
      }
      return result
    }

    // does not load anything, but we use it to set the original includes
    options.loadFromConditions = function(
      parentCollection,
      parentConditions,
      include
    ) {
      const includes = {}
      var tmpIncludes = includes

      // convert the array of through relations to an object.
      // e.g. ['a', 'b'] => {a: {b: {}}}
      options.through.forEach(function(relationName, index) {
        tmpIncludes[relationName] = {}

        // add sub includes
        if (index === options.through.length - 1 && include.children) {
          tmpIncludes[relationName] = include.children
        }

        tmpIncludes = tmpIncludes[relationName]
      })

      if (include.conditions) tmpIncludes.$conditions = include.conditions
      if (options.scope) tmpIncludes.$scope = options.scope
      if (include.args)
        tmpIncludes.$args = Array.isArray(include.args)
          ? include.args
          : [include.args]

      // include `through` relations instead
      parentCollection.include(includes)
    }

    options.loadFromRecords = function(parentCollection, include) {
      return Promise.resolve([]) // no need to load anything. `loadFromConditions` (via include) or `loadWithCollection` will handle all loading!
    }

    options.loadWithCollection = function(collection) {
      const parent = collection.getInternal('relation_to') || self.model.new(collection.getInternal('cloned_relation_to'))
      const chain = self.relations[options.through[0]].collection(parent)

      utils.assignInternals(chain, collection)
      collection.runScopes() // run scopes on original connection to check if it should return raw results

      const includes = {}
      const asRaw = collection.getInternal('as_raw')
      const joinOrInclude = asRaw ? 'join' : 'include'
      var tmpIncludes = includes

      // convert the array of through relations to an object.
      options.through.slice(1).forEach(function(relationName, index) {
        tmpIncludes[relationName] = {}
        tmpIncludes = tmpIncludes[relationName]
      })

      if (options.scope) tmpIncludes.$scope = options.scope
      
      chain.setInternal('through', options.through)
      if(asRaw) chain.clearInternal('relation')
      
      return chain[joinOrInclude](includes).then(function(result) {        
        if (asRaw) return result
        return options.filterCache(parent)
      })
    }

    options.filterCache = function(parentRecord) {
      var tmpRecords = [parentRecord]
      options.through.forEach(function(relationName) {
        const tmp = []
        tmpRecords.forEach(function(record) {
          const child = record['_' + relationName]

          if (!child) return

          if (Array.isArray(child)) tmp.push.apply(tmp, child)
          else tmp.push(child)
        })
        tmpRecords = tmp
      })
      const throughRecords = tmpRecords

      if (options.model) {
        const chain = options.model.chain()

        chain.add(throughRecords) // add all child records
        chain.setInternal('relation', options) // add the parent relation of this collection
        chain.setInternal('relation_to', parentRecord) // + the parent record
        chain._resolved() // set this collection as existing (all records fetched from the datastore!)

        if (options.type === 'has_one') return chain[0]
        return chain
      }

      if (options.type === 'has_one') return throughRecords[0]
      return throughRecords
    }

    options.collection = function(parentRecord) {
      if (options.targetRelation) {
        const chain = options.targetRelation.collection(parentRecord)
        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 `collection` function! (relation: ' +
          name +
          ')'
      )
    }

    options.add = function(parent, record) {
      if (options.through.length > 2)
        throw new Error(
          "Doesn't not work with a has many through over " +
            options.through.length +
            ' relations!'
        )

      // add records to the other relation
      const newRecord = {}
      newRecord[options.through[1]] = record
      parent[options.through[0]].add(newRecord)
    }

    // clear all records
    options.clear = function(parent, collection) {
      if (options.through.length > 2)
        throw new Error(
          "Doesn't not work with a has many through over " +
            options.through.length +
            ' relations!'
        )

      const through = options.through[0]
      var throughRel = parent.relations[through]
      if (!throughRel) {
        throughRel = parent[through]
        self.relations[through].setResult(parent, throughRel)
      }
      throughRel.clear()
    }

    options.afterSave = function(parent, saveOptions) {
      // will be handled by the real relations
    }

    return options
  }
1149535
public function initialize()
    {
        $this->setSource($this->tableName);
        $this->keepSnapshots(true);
        $this->hasMany('id', __NAMESPACE__ . '\UserRole', 'authuserentity_id', array('alias' => 'UserRoles', 'foreignKey' => array('action' => Relation::ACTION_CASCADE)));
        $this->hasMany('id', __NAMESPACE__ . '\Option', 'user_id', array('alias' => 'Options', 'foreignKey' => array('action' => Relation::ACTION_CASCADE)));
        $this->hasMany('id', __NAMESPACE__ . '\Protocol', 'user_id', array('alias' => 'Protocols', 'foreignKey' => array('action' => Relation::ACTION_CASCADE)));
        $this->hasMany('id', __NAMESPACE__ . '\Token', 'user_id', array('alias' => 'Tokens', 'foreignKey' => array('action' => Relation::ACTION_CASCADE)));
    }