#7869·gorm

M2M associations do not work with map and NoLowerCase used in the NamingStrategy

Author: P1cheneGCreated Sep 25, 2026Updated Sep 25, 2026
Labelstype:with reproduction steps

GORM Playground Link

https://github.com/go-gorm/playground/pull/862

Description

Association.Append with a map does not link a many-to-many association when NamingStrategy.NoLowerCase is true.

The related row is inserted with the correct primary key, but the join row is stored with an empty foreign key. After three appends, UserSpeaks contains one row whose LanguageCode is "", not three rows for am2m_map_1, am2m_map_2, and am2m_map_3. Association.Count returns 1.

This is not specific to Postgres. The same result shows up on SQLite, MySQL, and SQL Server.

Cause

In saveAssociation (association.go), map keys are lowercased before the field lookup:

go
k := strings.ToLower(key.String())
if f, ok := association.Relationship.FieldSchema.FieldsByDBName[k]; ok {

With NoLowerCase: true, the column name stays Code. FieldsByDBName has Code, not code, so the lookup misses and the in-memory primary key stays empty. That empty value is what gets written to UserSpeaks.LanguageCode.

Reproduction

go
package main

import (
	"fmt"
	"time"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type Language struct {
	Code string `gorm:"primarykey"`
	Name string
}

type User struct {
	gorm.Model
	Name      string
	Age       uint
	Birthday  *time.Time
	Languages []Language `gorm:"many2many:UserSpeak;"`
}

func main() {
	db, err := gorm.Open(postgres.Open("user=postgres password=1234 host=localhost port=5432 database=TEST"),
		&gorm.Config{NamingStrategy: schema.NamingStrategy{NoLowerCase: true}})
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := db.AutoMigrate(&User{}, &Language{}); err != nil {
		fmt.Println(err)
		return
	}

	birthday := time.Now().Round(time.Second)
	user := User{Name: "assoc_m2m_append_map", Age: 18, Birthday: &birthday}
	if err := db.Create(&user).Error; err != nil {
		fmt.Println(err)
		return
	}

	maps := []map[string]interface{}{
		{"Code": "am2m_map_1", "Name": "AppendMap1"},
		{"Code": "am2m_map_2", "Name": "AppendMap2"},
		{"Code": "am2m_map_3", "Name": "AppendMap3"},
	}
	for _, row := range maps {
		if err := db.Model(&user).Association("Languages").Append(row); err != nil {
			fmt.Println(err)
			return
		}
	}

	if count := db.Model(&user).Association("Languages").Count(); count != 3 {
		fmt.Printf("languages count: got %d, want 3\n", count)
		return
	}
}

Map keys are Code and Name, which are the column names produced by NoLowerCase.

Expected

Three UserSpeaks rows, with LanguageCode set to am2m_map_1, am2m_map_2, and am2m_map_3. Count() returns 3.

Actual

Count() returns 1. UserSpeaks has a single row with LanguageCode = "".