Add the foreign key for the belongs_to relationships
772874
def add_foreign_keys_as_attributes
      @@reflections[self.class.name.to_sym][:belongs_to].each do |klass|
        add_attribute klass.to_s.foreign_key.to_sym
      end
    end
1170691
public function addForeignKeys()
    {        
        $this->addForeignKey(null, $this->tableName, ['elementId'], '{{%elements}}', ['id'], 'CASCADE', null);
        $this->addForeignKey(null, $this->tableName, ['siteId'], '{{%sites}}', ['id'], 'CASCADE', 'CASCADE');
    }
453680
def belongs_to(parent_resource)
        parent_resource = parent_resource.to_sym
        parent_resources << parent_resource unless parent_resource.in?(parent_resources)
      end
737675
public function addConstraints()
    {
        if (static::$hasConstraints) {
            // For belongs to relationships, which are essentially the inverse of has one
            // or has many relationships, we need to actually query on the primary key
            // of the related models matching on the foreign key that's on a parent.
            $foreign_keyValue = $this->parent->getAttribute($this->foreign_key);
            $this->query->where($this->local_key, '=', $foreign_keyValue);
        }
    }
1068934
def db_belongs_to(name, scope = nil, **options)
      Helpers.cache_valid_method!(self)

      @database_validations_storage ||= DatabaseValidations::OptionsStorage.new(self)

      belongs_to_options =
        if ActiveRecord::VERSION::MAJOR < 5
          options.delete(:optional)
          options.merge(required: false)
        else
          options.merge(optional: true)
        end

      belongs_to(name, scope, belongs_to_options)

      foreign_key = reflections[name.to_s].foreign_key

      @database_validations_storage.push_belongs_to(foreign_key, name)

      validates_with DatabaseValidations::DBPresenceValidator,
                     DatabaseValidations::BelongsToOptions.validator_options(name, foreign_key)

      include(DatabaseValidations::Rescuer)
    end
795967
def belongs_to_identity(assoc, options={})
      other_model = assoc.to_s.camelize.constantize
      fk = :"#{other_model.model_name.to_s.underscore}_identity"
      if defined?(@slowly_changing_columns)
        @slowly_changing_columns << [fk, other_model.identity_column_definition.last]
        @slowly_changing_indices << fk
      end
      if ActiveRecord::VERSION::MAJOR > 3
        belongs_to assoc, ->{ where "#{other_model.effective_to_column_sql()}=#{END_OF_TIME}" },
                   options.reverse_merge(foreign_key: fk, primary_key: IDENTITY_COLUMN)
      else
        belongs_to assoc, options.reverse_merge(
                            foreign_key: fk, primary_key: IDENTITY_COLUMN,
                            conditions: "#{other_model.effective_to_column_sql()}=#{END_OF_TIME}"
                          )
      end
      define_method :"#{assoc}_at" do |date=nil|
        other_model.at(date).where(IDENTITY_COLUMN=>send(fk)).first
      end
    end
1337429
def joins(self, table):
        

        def do_join(table, model):
            while model is not associations.model_from_name(table):
                # ex) Category -> Forum -> Thread -> Post
                # Category: {"posts": "forums"}
                # Forum: {"posts": "threads"}
                # Thread: {"posts": None}
                # >>> Category.joins("posts")
                # => [
                #       {'table': 'forums', 'on': ['category_id', 'id']}
                #       {'table': 'threads', 'on': ['forum_id', 'id']}
                #       {'table': 'posts', 'on': ['thread_id', 'id']}
                #    ]
                if table in associations.associations_for(model):
                    # This to next: one-many (they have the fk)
                    # If associations.associations_for(model)[table] is None, then this is
                    # terminal (i.e. table is the FINAL association in the
                    # chain)
                    next_level = associations.associations_for(model)[table] or table
                    next_model = associations.model_from_name(next_level)
                    foreign_key = associations.foreign_keys_for(model).get(
                        next_level,
                        inflector.foreignKey(model.__name__))
                    yield {'table': next_level, 'on': [foreign_key, 'id']}
                else:
                    # One-One or Many-One
                    # singular table had better be in associations.associations_for(model)
                    singular = inflector.singularize(table)
                    next_level = associations.associations_for(model)[singular] or singular
                    next_model = associations.model_from_name(next_level)
                    this_table_name = Repo.table_name(model)
                    foreign_key = associations.foreign_keys_for(model).get(
                        next_level,
                        inflector.foreignKey(model.__name__))
                    if associations.model_has_foreign_key_for_table(table,
                                                                    model):
                        # we have the foreign key
                        order = ['id', foreign_key]
                    else:
                        # They have the foreign key
                        order = [foreign_key, 'id']
                    yield {'table': inflector.pluralize(next_level), 'on': order}
                model = next_model

        self.join_args = list(do_join(table, self.model))
        return self
681810
public function addConstraints()
    {
        parent::addConstraints();

        if (static::$constraints) {
            if (is_array($this->foreignKeys[0])) {
                $column = $this->throughParent->qualifyColumn($this->foreignKeys[0][0]);

                $this->query->where($column, '=', $this->farParent->getMorphClass());
            }
        }
    }
1151927
protected function addForeignKeys()
    {
        $this->addForeignKey(
            $this->db->getForeignKeyName(TokensRecord::tableName(), 'providerId'),
            TokensRecord::tableName(),
            'providerId',
            ProviderRecord::tableName(),
            'id',
            'CASCADE'
        );
    }
1264811
static function TableKeyHasMany($table, $tablePKey, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
	{
		if (!is_array($tablePKey)) {
			$tablePKey = array($tablePKey);
		}
		$ar = new ADODB_Active_Record($table,$tablePKey);
		$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
	}
380184
public function addConstraints()
    {
        if (static::$constraints) {
            $table = $this->related->getTable();

            $this->query->where($table.'.'.$this->otherKey, '=', $this->parent->{$this->foreignKey});
        }
    }
94324
public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
    {
        // If no relation name was given, we will use this debug backtrace to extract
        // the calling method's name and use that as the relationship name as most
        // of the time this will be what we desire to use for the relationships.
        if (is_null($relation)) {
            list($current, $caller) = debug_backtrace(false, 2);

            $relation = $caller['function'];
        }

        $specialType = $this->getCmsSpecialRelationType($relation);

        // If no foreign key was supplied, we can use a backtrace to guess the proper
        // foreign key name by using the name of the relationship function, which
        // when combined with an "_id" should conventionally match the columns.
        if (is_null($foreignKey)) {
            if ($specialType === self::RELATION_TYPE_CATEGORY) {
                $foreignKey = config('pxlcms.relations.categories.keys.category');
            } else {
                $foreignKey = Str::snake($relation);
            }
        }

        // If the relation name is the same (casing aside) as the foreign key attribute,
        // we must make sure that the foreign key property is at least a key in the
        // attributes array. If it is not, there will be recursive lookup problems
        // where the attribute is never resolved and 'property does not exist' exceptions occur.
        if (    snake_case($relation) == $foreignKey
            &&  ! array_key_exists($foreignKey, $this->attributes)
        ) {
            $this->attributes[ $foreignKey ] = null;
        }

        /** @var Builder $belongsTo */
        $belongsTo = parent::belongsTo($related, $foreignKey, $otherKey, $relation);

        // category relation must be filtered by module id
        if ($specialType === self::RELATION_TYPE_CATEGORY) {
            $belongsTo->where(
                config('pxlcms.relations.categories.keys.module'),
                $this->getModuleNumber()
            );
        }

        return $belongsTo;
    }
74272
function addForeignKey($table, $pkname, $tables)
	{
		if ( is_string($tables) )
			$tables = array($tables);
			
		
		$this->_foreignKeys[$table] = array(
					'primaryKey' => $pkname,
					'tables' => $tables
				);
	}
790768
def add_index(columns, index_name = nil)
      options = { name: index_name } if index_name
      migration.add_index(table_name, columns, options || {})
    end
1094011
def _process_foreign_keys(cls, foreign_keys, node_data):
        
        for key in foreign_keys.keys():
            if key in node_data:
                node_data[key] = foreign_keys[key].objects.get(
                    pk=node_data[key])
878310
def associate(self, model):
        
        self._parent.set_attribute(self._foreign_key, model.get_key())
        self._parent.set_attribute(self._morph_type, model.get_morph_class())

        return self._parent.set_relation(self._relation, model)
1058671
async def add_relation(self, local_relation, remote_relation):
        
        if ':' not in local_relation:
            local_relation = '{}:{}'.format(self.name, local_relation)

        return await self.model.add_relation(local_relation, remote_relation)