The join table's name needs to be UserLanguages
. But GORM always creates the table as user_languages
.
type User struct {
gorm.Model
Languages []*Language `gorm:"many2many:UserLanguages;"`
}
type Language struct {
gorm.Model
Name string
Users []*User `gorm:"many2many:UserLanguages;"`
}
How can I change the name of the join table?
I found NamingStrategy in GORM's docs:
GORM allows users to change the naming conventions by overriding the default NamingStrategy which need to implements interface Namer
But whatever I tried I couldn't get it work. Maybe someone has an example?
Gorm will try to convert CamelCase to snake_case because that's the common naming convention for tables in most databases.
The camel to snake case conversion will also be applied in your case, on the many2many
table name annotation. E.g.: if you'd use AaaBbbCccDdd, you would end up with a join table named aaa_bbb_ccc_ddd
To change the default behavior, you can override the NoLowerCase
value to true
in the naming strategy of the gorm config.
package main
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
type User struct {
gorm.Model
Languages []*Language `gorm:"many2many:UserLanguages;"`
}
type Language struct {
gorm.Model
Name string
Users []*User `gorm:"many2many:UserLanguages;"`
}
func main() {
db, err := gorm.Open(sqlite.Open("mydb.db"), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
NoLowerCase: true, // << HERE
},
})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&User{})
db.AutoMigrate(&Language{})
}
If you really need to override the JoinTableName method, although you probably don't need to, you can do something as shown below, and you will end up with join table named UserLanguages_OVERRIDE_HERE
type MyCustomNaming struct {
schema.NamingStrategy
}
func (MyCustomNaming) JoinTableName(table string) string {
return table + "_OVERRIDE_HERE"
}
func main() {
ns := MyCustomNaming{
NamingStrategy: schema.NamingStrategy{
NoLowerCase: true,
},
}
db, err := gorm.Open(sqlite.Open("mydb.db"), &gorm.Config{
NamingStrategy: ns,
})
...