GORM don't use underscores in tablenames

Viewed 86

I'm attempting to use GORM with a database originally developed with Django.

The issue I'm running into is that the tables created by Django follow the format app_name_tablename. I am using the TablePrefix option to add that app_name_ part, but I cannot find an option to prevent GORM from automatically using underscores in the name. The Gorm docs don't seem to reference an option to remove this underscore.

Obviously I can define the tablename manually on each of the models, however I'd rather avoiding doing this. Is there an option in the Gorm config to do this automatically?

2 Answers

You can try NoLowerCase

db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
  NamingStrategy: schema.NamingStrategy{
    TablePrefix: "t_",   // table name prefix, table for `User` would be `t_users`
    SingularTable: true, // use singular table name, table for `User` would be `user` with this option enabled
    NoLowerCase: true, // skip the snake_casing of names
    NameReplacer: strings.NewReplacer("CID", "Cid"), // use name replacer to change struct/field name before convert it to db name
  },
})

https://gorm.io/docs/gorm_config.html#NamingStrategy

You can implement the TableName() string function in your entity which will force gorm to use that name.

e.g:

type OrganizationGroup struct {
  Name string
}

func (o OrganizationGroup) TableName() string {
    return "OrganizationGroups"
}
Related