{"record":{"id":"4c7a520dbfc80e9f","repo":"go-gorm/gorm","slug":"failed-to-assign-association-v-make-sure-foreig","errorCode":null,"errorMessage":"failed to assign association %#v, make sure foreign fields exists","messagePattern":"failed to assign association %#v, make sure foreign fields exists","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"callbacks/preload.go","lineNumber":327,"sourceCode":"\t\tfor i := 0; i < reflectValue.Len(); i++ {\n\t\t\tswitch rel.Type {\n\t\t\tcase schema.HasMany, schema.Many2Many:\n\t\t\t\ttx.AddError(rel.Field.Set(tx.Statement.Context, reflectValue.Index(i), reflect.MakeSlice(rel.Field.IndirectFieldType, 0, 10).Interface()))\n\t\t\tdefault:\n\t\t\t\ttx.AddError(rel.Field.Set(tx.Statement.Context, reflectValue.Index(i), reflect.New(rel.Field.FieldType).Interface()))\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < reflectResults.Len(); i++ {\n\t\telem := reflectResults.Index(i)\n\t\tfor idx, field := range relForeignFields {\n\t\t\tfieldValues[idx], _ = field.ValueOf(tx.Statement.Context, elem)\n\t\t}\n\n\t\tdatas, ok := identityMap[utils.ToStringKey(fieldValues...)]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"failed to assign association %#v, make sure foreign fields exists\", elem.Interface())\n\t\t}\n\n\t\tfor _, data := range datas {\n\t\t\treflectFieldValue := rel.Field.ReflectValueOf(tx.Statement.Context, data)\n\t\t\tif reflectFieldValue.Kind() == reflect.Ptr && reflectFieldValue.IsNil() {\n\t\t\t\treflectFieldValue.Set(reflect.New(rel.Field.FieldType.Elem()))\n\t\t\t}\n\n\t\t\treflectFieldValue = reflect.Indirect(reflectFieldValue)\n\t\t\tswitch reflectFieldValue.Kind() {\n\t\t\tcase reflect.Struct:\n\t\t\t\ttx.AddError(rel.Field.Set(tx.Statement.Context, data, elem.Interface()))\n\t\t\tcase reflect.Slice, reflect.Array:\n\t\t\t\tif reflectFieldValue.Type().Elem().Kind() == reflect.Ptr {\n\t\t\t\t\ttx.AddError(rel.Field.Set(tx.Statement.Context, data, reflect.Append(reflectFieldValue, elem).Interface()))\n\t\t\t\t} else {\n\t\t\t\t\ttx.AddError(rel.Field.Set(tx.Statement.Context, data, reflect.Append(reflectFieldValue, elem.Elem()).Interface()))\n\t\t\t\t}","sourceCodeStart":309,"sourceCodeEnd":345,"githubUrl":"https://github.com/go-gorm/gorm/blob/1d6ce99528060be18a42be09aca8d39efcb47f28/callbacks/preload.go#L309-L345","documentation":"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.","triggerScenarios":"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.","commonSituations":"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).","solutions":["Check the relation's foreignKey/references gorm tags against the actual columns (names, order for composite keys).","Exclude NULL-FK rows with a preload condition: db.Preload(clause.Associations) or Preload(\"Orders\", \"user_id IS NOT NULL\").","Confirm FK and PK column types match (string vs int breaks ToStringKey matching).","Reproduce with a small query printing both sides' key values to see the mismatch."],"exampleFix":"// before\ntype Order struct {\n  UserID *uint // nullable FK -> NULL rows break assignment\n}\ndb.Preload(\"Orders\").Find(&users)\n\n// after\ndb.Preload(\"Orders\", \"user_id IS NOT NULL\").Find(&users)","handlingStrategy":"validation","validationCode":"// before preloading, confirm FK columns are non-nullable and tag-mapped\ntype Order struct {\n    UserID uint `gorm:\"not null\"` // non-nullable FK avoids NULL mismatch\n}\n// or filter explicitly:\ndb.Preload(\"Orders\", \"user_id IS NOT NULL\").Find(&users)","typeGuard":null,"tryCatchPattern":"if err := db.Preload(\"Orders\").Find(&users).Error; err != nil {\n    if strings.Contains(err.Error(), \"failed to assign association\") {\n        // inspect FK values vs owner PKs; fix tags or add preload condition\n    }\n    return err\n}","preventionTips":["Declare composite FKs in the same order as the referenced primary keys.","Keep FK and PK Go/SQL types identical (both uint, both string).","Avoid nullable FKs on preloaded relations, or exclude NULL rows with preload conditions."],"tags":["gorm","preload","foreign-key","associations","data-integrity"],"backgroundTag":null,"analyzedSha":"1d6ce99528060be18a42be09aca8d39efcb47f28","analyzedAt":"2026-08-15T13:01:23.433Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}