It's kind of redundant to have the server return the foreign
 keys corresponding to the belongs_to associations (since they'll
 be in the URL anyway), so we'll try to inject them based on the
 attributes of the object we just used.
571
def load(attributes, remove_root=false)
      attributes = attributes ? attributes.stringify_keys : {}
      self.class.belongs_to_with_parents.each do |belongs_to_param|
        attributes["#{belongs_to_param}_id"] ||= prefix_options["#{belongs_to_param}_id".intern]

        # also set prefix attributes as real attributes. Otherwise,
        # belongs_to attributes will be stripped out of the response
        # even if we aren't actually using the association.
        @attributes["#{belongs_to_param}_id"] = attributes["#{belongs_to_param}_id"]
      end
      super(attributes, remove_root)
    end
1193276
def _model_foreign(ins):
    
    fks = []
    for t in ins.tables:
        fks.extend([
            SaForeignkeyDoc(
                key=fk.column.key,
                target=fk.target_fullname,
                onupdate=fk.onupdate,
                ondelete=fk.ondelete
            )
            for fk in t.foreign_keys])
    return fks
1350556
static function TableHasMany($table, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
	{
		$ar = new ADODB_Active_Record($table);
		$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
	}
1163439
private String getRefSQL(ForeignKeyConstraint fk) {

		Set<Object> columns = new LinkedHashSet<>(); // Set avoids duplicated and LinkedHashSet keeps the insertion order
		for (Attribute attr : getIdentifyingAttributes(fk.getRelation()))
			columns.add(getColumnNameWithAlias(attr));

		List<String> conditions = new ArrayList<>(fk.getComponents().size());
		for (ForeignKeyConstraint.Component comp : fk.getComponents()) {
			columns.add(getColumnNameWithAlias(comp.getReference()));	
			conditions.add(getColumnName(comp.getAttribute()) + " = " + getColumnName(comp.getReference()));
		}
		
		for (Attribute attr : getIdentifyingAttributes(fk.getReferencedRelation())) 
			columns.add(getColumnNameWithAlias(attr));

		final String tables = fk.getRelation().getID().getSQLRendering() + 
							", " + fk.getReferencedRelation().getID().getSQLRendering();
		
		return String.format("SELECT %s FROM %s WHERE %s", 
				Joiner.on(", ").join(columns), tables, Joiner.on(" AND ").join(conditions));
	}
56813
function injectFKs(row, fks) {
	_.forEach(fks, function(fk, id) {
		if (!_.has(row, id)) return; // Skip omitted FK refs

		var lookupKey = _.get(row, id);
		switch (fk.type) {
			case FK_OBJECTID: // 1:1 relationship
				if (!settings.refs[lookupKey])
					throw new Error('Attempting to inject non-existant reference "' + row[lookupKey] + '" (from lookup ref "' + lookupKey + '") into field path "' + id + '" before its been created!');
				_.set(row, id,  settings.refs[lookupKey]);
				break;
			case FK_OBJECTID_ARRAY: // 1:M array based relationship
				_.set(row, id, _.map(lookupKey, function(fieldValueArr) { // Resolve each item in the array
					if (!settings.refs[fieldValueArr])
						throw new Error('Attempting to use reference "' + fieldValueArr + '" in 1:M field path "' + id + '" before its been created!');
					return settings.refs[fieldValueArr];
				}));
				break;
			case FK_SUBDOC: // Mongo subdocument
				_.forEach(_.get(row, id), function(subdocItem, subdocIndex) {
					injectFKs(subdocItem, fks[id].fks);
				});
				break;
		}
	});
}
962378
def txn_getAssociation(self, server_url, handle=None):
        
        if handle is not None:
            self.db_get_assoc(server_url, handle)
        else:
            self.db_get_assocs(server_url)

        rows = self.cur.fetchall()
        if len(rows) == 0:
            return None
        else:
            associations = []
            for values in rows:
                values = list(values)
                values[1] = self.blobDecode(values[1])
                assoc = Association(*values)
                if assoc.expiresIn == 0:
                    self.txn_removeAssociation(server_url, assoc.handle)
                else:
                    associations.append((assoc.issued, assoc))

            if associations:
                associations.sort()
                return associations[-1][1]
            else:
                return None
1271870
public function encode()
    {
        if (!empty($this->attributes)) {
            foreach ($this->attributes as $name => $params) {
                if (is_numeric($name)) {
                    $name = $params;
                }
                /** @var ActiveRecord $owner */
                $owner = $this->owner;
                if ($owner->hasAttribute($name)) {
                    $owner->setAttribute($name, Json::encode($owner->getAttribute($name)));
                }
            }
        }
    }
319526
def joins
      return nil if inner_joins.empty?
      inner_joins.collect do |inner_join|
        join_table_name = association_class(inner_join).table_name
        join_on_field = inner_join.last.to_s
        "INNER JOIN #{join_table_name} ON #{join_table_name}.id = #{table_name}.#{join_on_field}"
      end
    end
309041
def save_belongs_to_association(reflection)
      association = association_instance_get(reflection.name)
      record      = association && association.load_target
      if record && !record.destroyed?
        autosave = reflection.options[:autosave]

        if autosave && record.marked_for_destruction?
          record.destroy
        elsif autosave != false
          saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)

          if association.updated?
            association_id = record.send(reflection.options[:primary_key] || :id)
            self[reflection.foreign_key] = association_id
            association.loaded!
          end

          saved if autosave
        end
      end
    end
436413
function(params) {
		var me = this;

		if (Object.keys(model.columns).length == 0) {
			logger.error("Attempting to initialize `" + model.ident + "` instance before filling schema!");
			return null;
		} else if (model.primary === undefined) {
			logger.error("No primary key found for `" + model.ident + "`!");
			return null;
		}

		Object.defineProperty(me, 'values', {
			value: {},
			enumerable: false,
			writable: true,
			configurable: true,
		}); // Raw column values, accessed by setter/getter functions.

		params = params || {};

		/* --- Instance Methods --- */

		/**
		 * Saves the object's properties corresponding to table columns into the database.
		 */
		function save() {
			var act = new NobleMachine(function() {
				setStrs = [];

				for (var key in model.columns) {
					if ([model.primary].indexOf(key) == -1 && me[key] !== undefined) {
						setStrs.push('`' + key + '`' + " = " + nrutil.serialize(me[key]));
					}
				}

				if (model.columns['updatedAt'])
					setStrs.push('`updatedAt` = NOW()');

				var sql;
				if (me[model.primary]) {
					sql = "UPDATE " + model.table
							+ " SET " + setStrs.join(',')
							+ " WHERE `" + model.primary + "` = " + me[model.primary];
				} else {
					if (model.columns['createdAt'])
						setStrs.push('`createdAt` = NOW()');

					sql = "INSERT"
							+ " INTO " + model.table
							+ " SET " + setStrs.join(',');
				}


				act.toNext(db_query(sql));
			});

			act.next(function(result) {
				//log.debug("RESULT: " + JSON.stringify(result));

				if (result.insert_id) {
					me[model.primary] = result.insert_id;
				} else if (!me[model.primary]) {
					act.toError("No insert_id, and no extant primary key!");
					return;
				}

				
				logger.log("Successfully saved `" + model.ident + "` record `" + me[model.primary] + "`");

				act.toNext(me);
			});

			act.error(function(err) {
				logger.error("Error saving `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		/**
		 * Reloads the object's properties with the current database values.
		 */
		function reload() {
			var params = {}

			params[model.primary] = me[model.primary]
		
			var act = new NobleMachine(model.find(params));

			act.next(function(newInst) {
				if (newInst) {
					for (var col in model.columns) {
						me[col] = newInst[col];
					}

					act.toNext(me);
				} else {
					for (var key in model.columns) {
						me[key] = undefined
					}

					act.toNext(null);
				}
			});

			return act;
		}

		/**
		 * Removes this object's corresponding database row.
		 */
		function destroy() {
			var act = new NobleMachine(function() {
				if (me.onDestroy) {
					var preact = me.onDestroy();
					if (preact && preact.start instanceof Function) {
						act.toNext(preact)
						return;
					}
				}
			});

			act.next(function() {
				var sql = "DELETE FROM " + model.table
						+ " WHERE `" + model.primary + "` = " + me[model.primary];

				act.toNext(db_query(sql));
			});

			act.next(function() {
				logger.log("Successfully deleted `" + model.ident + "` record `" + me[model.primary] + "`");

				for (var param in me) {
					delete me[param];	
				}
			});

			act.error(function(err) {
				logger.error("Error deleting `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		// Generic setter for SQL-correspondent values. Forces typecasting for database compatibility.
		function setValue(key, val) {
			//util.log(key + ": " + JSON.stringify(val));

			if (val === null) {
				me.values[key] = null;
			} else if (val === undefined) {
				me.values[key] = undefined;
			} else {
				type = model.columns[key]['DATA_TYPE'];

				switch (type) {
					case 'datetime':
					case 'timestamp':
						me.values[key] = new Date(val);
						break;
					case 'text':
					case 'varchar':
						me.values[key] = val.toString();
						break;
					case 'int':
					case 'tinyint':
						if (model.columns[key]['COLUMN_TYPE'] == 'tinyint(1)') {
							me.values[key] = !!val // Boolean
						} else {
							me.values[key] = parseInt(val);
						}
						break;
					default:
						me.values[key] = val;
				}
			}
		}

		// Generic getter for SQL-correspondent values.
		function getValue(key) {
			return me.values[key];
		}

		for (var key in model.columns) {
			me.__defineSetter__(key, setValue.bind(me, key));
			me.__defineGetter__(key, getValue.bind(me, key));

			if (params[key] !== undefined) {
				setValue(key, params[key]);
			}
		}

		_.extend(me, {
			save: save,
			reload: reload,
			destroy: destroy,
			setValue: setValue
		});

		if (defFunc !== undefined) {
			defFunc(me);
		}

		return me;
	}
914036
function getAssociation($server_url, $handle = null)
    {
        // simple case: handle given
        if ($handle !== null) {
            // get association, return null if failed
            $association = $this->connection->get(
                $this->associationKey($server_url, $handle));
            return $association ? $association : null;
        }

        // no handle given, working with list
        // create key for list of associations
        $serverKey = $this->associationServerKey($server_url);

        // get list of associations
        $serverAssociations = $this->connection->get($serverKey);
        // return null if failed or got empty list
        if (!$serverAssociations) {
            return null;
        }

        // get key of most recently issued association
        $keys = array_keys($serverAssociations);
        sort($keys);
        $lastKey = $serverAssociations[array_pop($keys)];

        // get association, return null if failed
        $association = $this->connection->get($lastKey);
        return $association ? $association : null;
    }
453680
def belongs_to(parent_resource)
        parent_resource = parent_resource.to_sym
        parent_resources << parent_resource unless parent_resource.in?(parent_resources)
      end
870094
function storeAssociation($server_url, $association)
    {
        // create memcached keys for association itself
        // and list of associations for this server
        $associationKey = $this->associationKey($server_url,
            $association->handle);
        $serverKey = $this->associationServerKey($server_url);

        // get list of associations
        $serverAssociations = $this->connection->get($serverKey);

        // if no such list, initialize it with empty array
        if (!$serverAssociations) {
            $serverAssociations = array();
        }
        // and store given association key in it
        $serverAssociations[$association->issued] = $associationKey;

        // save associations' keys list
        $this->connection->set(
            $serverKey,
            $serverAssociations,
            $this->compress
        );
        // save association itself
        $this->connection->set(
            $associationKey,
            $association,
            $this->compress,
            $association->issued + $association->lifetime);
    }
518547
static function ClassHasMany($parentclass, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
	{
		$ar = new $parentclass();
		$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
	}
132748
function (parent) {
            var options = this.__opts || {};
            var ds, self = this;
            if (!isUndefined((ds = options.dataset)) && isFunction(ds)) {
                ds = ds.apply(parent, [parent]);
            }
            if (!ds) {
                var q = {};
                this._setAssociationKeys(parent, q);
                ds = this.model.dataset.naked().filter(q);
                var recip = this.model._findAssociation(this);
                recip && (recip = recip[1]);
                ds.rowCb = function (item) {
                    var model = self._toModel(item, true);
                    recip && recip.__setValue(model, parent);
                    //call hook to finish other model associations
                    return model._hook("post", "load").chain(function () {
                        return model;
                    });
                };
            } else if (!ds.rowCb && this.model) {
                ds.rowCb = function (item) {
                    var model = self._toModel(item, true);
                    //call hook to finish other model associations
                    return model._hook("post", "load").chain(function () {
                        return model;
                    });
                };
            }

            return this._setDatasetOptions(ds);
        }
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)
128363
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        
        db = kwargs.get('using')
        if db_field.name in self.raw_id_fields:
            kwargs['widget'] = PolymorphicForeignKeyRawIdWidget(
                db_field.rel,
                admin_site=self._get_child_admin_site(db_field.rel),
                using=db
            )
            if 'queryset' not in kwargs:
                queryset = self.get_field_queryset(db, db_field, request)
                if queryset is not None:
                    kwargs['queryset'] = queryset
            return db_field.formfield(**kwargs)
        return super(PolymorphicAdminRawIdFix, self).formfield_for_foreignkey(
            db_field, request=request, **kwargs)