go-gorm/gorm · error

failed to assign association %#v, make sure foreign fields e

Error message

failed to assign association %#v, make sure foreign fields exists

What it means

After loading related rows for a preload, GORM groups owners in an identityMap keyed by the relation's foreign-field values. When a related row's foreign key values (fieldValues from relForeignFields) have no entry in identityMap, assignment is impossible and it returns fmt.Errorf("failed to assign association %#v, make sure foreign fields exists", elem.Interface()). It indicates the FK columns on related rows point at owner key values GORM did not collect - usually NULLs or a FK/key mismatch.

Source

Thrown at callbacks/preload.go:327

		for i := 0; i < reflectValue.Len(); i++ {
			switch rel.Type {
			case schema.HasMany, schema.Many2Many:
				tx.AddError(rel.Field.Set(tx.Statement.Context, reflectValue.Index(i), reflect.MakeSlice(rel.Field.IndirectFieldType, 0, 10).Interface()))
			default:
				tx.AddError(rel.Field.Set(tx.Statement.Context, reflectValue.Index(i), reflect.New(rel.Field.FieldType).Interface()))
			}
		}
	}

	for i := 0; i < reflectResults.Len(); i++ {
		elem := reflectResults.Index(i)
		for idx, field := range relForeignFields {
			fieldValues[idx], _ = field.ValueOf(tx.Statement.Context, elem)
		}

		datas, ok := identityMap[utils.ToStringKey(fieldValues...)]
		if !ok {
			return fmt.Errorf("failed to assign association %#v, make sure foreign fields exists", elem.Interface())
		}

		for _, data := range datas {
			reflectFieldValue := rel.Field.ReflectValueOf(tx.Statement.Context, data)
			if reflectFieldValue.Kind() == reflect.Ptr && reflectFieldValue.IsNil() {
				reflectFieldValue.Set(reflect.New(rel.Field.FieldType.Elem()))
			}

			reflectFieldValue = reflect.Indirect(reflectFieldValue)
			switch reflectFieldValue.Kind() {
			case reflect.Struct:
				tx.AddError(rel.Field.Set(tx.Statement.Context, data, elem.Interface()))
			case reflect.Slice, reflect.Array:
				if reflectFieldValue.Type().Elem().Kind() == reflect.Ptr {
					tx.AddError(rel.Field.Set(tx.Statement.Context, data, reflect.Append(reflectFieldValue, elem).Interface()))
				} else {
					tx.AddError(rel.Field.Set(tx.Statement.Context, data, reflect.Append(reflectFieldValue, elem.Elem()).Interface()))
				}

View on GitHub (pinned to 1d6ce99528)

Solutions

  1. Check the relation's foreignKey/references gorm tags against the actual columns (names, order for composite keys).
  2. Exclude NULL-FK rows with a preload condition: db.Preload(clause.Associations) or Preload("Orders", "user_id IS NOT NULL").
  3. Confirm FK and PK column types match (string vs int breaks ToStringKey matching).
  4. Reproduce with a small query printing both sides' key values to see the mismatch.

Example fix

// before
type Order struct {
  UserID *uint // nullable FK -> NULL rows break assignment
}
db.Preload("Orders").Find(&users)

// after
db.Preload("Orders", "user_id IS NOT NULL").Find(&users)
Defensive patterns

Strategy: validation

Validate before calling

// before preloading, confirm FK columns are non-nullable and tag-mapped
type Order struct {
    UserID uint `gorm:"not null"` // non-nullable FK avoids NULL mismatch
}
// or filter explicitly:
db.Preload("Orders", "user_id IS NOT NULL").Find(&users)

Try / catch

if err := db.Preload("Orders").Find(&users).Error; err != nil {
    if strings.Contains(err.Error(), "failed to assign association") {
        // inspect FK values vs owner PKs; fix tags or add preload condition
    }
    return err
}

Prevention

When it happens

Trigger: Preloading has-many/many-to-many where related rows have NULL foreign keys (soft-archived rows), composite foreign keys declared in a different order than the primary key, or custom foreignKey/references tags whose column mapping does not line up, so utils.ToStringKey(fieldValues...) never matches an owner key.

Common situations: Declaring composite FKs with mismatched column order in tags; LEFT JOIN-generated rows with NULL join values; polymorphic relations with wrong foreignKey tags; data written by other systems where FK values reference owners outside the current result set with type mismatches (string vs int keys).

Related errors


AI-assisted analysis of go-gorm/gorm@1d6ce99528 (2026-08-15). Data as JSON: /api/errors/4c7a520dbfc80e9f. Report an issue: GitHub.