GORM不在表名中使用下划线。

huangapple go评论97阅读模式
英文:

GORM don't use underscores in tablenames

问题

我正在尝试将GORM与最初使用Django开发的数据库一起使用。

我遇到的问题是,Django创建的表遵循app_name_tablename的格式。我正在使用TablePrefix选项来添加app_name_部分,但我找不到一个选项来阻止GORM自动在名称中使用下划线。Gorm文档似乎没有提到删除这个下划线的选项。

显然,我可以在每个模型上手动定义表名,但我宁愿避免这样做。在Gorm配置中是否有一个选项可以自动完成这个操作?

英文:

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?

答案1

得分: 1

你可以尝试使用NoLowerCase选项。

db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
  NamingStrategy: schema.NamingStrategy{
    TablePrefix: "t_",   // 表名前缀,`User`的表名将变为`t_users`
    SingularTable: true, // 使用单数表名,启用此选项后,`User`的表名将变为`user`
    NoLowerCase: true, // 跳过名称的蛇形命名
    NameReplacer: strings.NewReplacer("CID", "Cid"), // 在将结构体/字段名称转换为数据库名称之前,使用名称替换器更改名称
  },
})

更多信息请参考:GORM 配置文档

英文:

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

答案2

得分: 0

你可以在实体中实现TableName() string函数,这将强制gorm使用该名称。

例如:

type OrganizationGroup struct {
  Name string
}

func (o OrganizationGroup) TableName() string {
    return "OrganizationGroups"
}
英文:

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"
}

huangapple
  • 本文由 发表于 2022年5月30日 05:20:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/72427371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定