How to set singular name for a table in gorm

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

How to set singular name for a table in gorm

问题

我想使用这个模型创建一个名为'user'的表。但是表名自动设置为'users'。我知道这是gorm的默认行为。但是我希望表名为'user'。

英文:
type user struct {
	ID       int
	Username string `gorm:"size:255"`
	Name     string `gorm:"size:255"`
}

I want to create a table 'user' using this model. But the table name is automatically set to 'users'. I know it is gorm's default behavior. But I want the table name to be 'user'.

答案1

得分: 50

为你的结构体设置TableName方法。

func (user) TableName() string {
    return "user"
}

链接:https://gorm.io/docs/models.html#conventions

英文:

Set method TableName for your struct.

func (user) TableName() string {
	return "user"
}

Link: https://gorm.io/docs/models.html#conventions

答案2

得分: 21

Gorm内置了一个方法,可以在全局级别设置所有表的单数形式。

对于Gorm v1,你可以这样做:

db.SingularTable(true)

对于v2,稍微冗长一些:

db, err := gorm.Open(postgres.Open(connStr), &gorm.Config{
	NamingStrategy: schema.NamingStrategy{
		SingularTable: true,
	},
})
英文:

Gorm has a in-built method for that that will be set in global level so all tables will be singular.

For gorm v1, you could do:

db.SingularTable(true)

For v2, it's a little more verbose:

db, err := gorm.Open(postgres.Open(connStr), &gorm.Config{
	NamingStrategy: schema.NamingStrategy{
		SingularTable: true,
	},
})

答案3

得分: 0

要显式设置表名,您需要创建一个带有TableName方法的接口Tabler,然后为结构体创建一个接收器方法(在接口中定义):

type user struct {
    ID       int
    Username string `gorm:"size:255"`
    Name     string `gorm:"size:255"`
}

type Tabler interface {
  TableName() string
}

// TableName将User使用的表名覆盖为`profiles`
func (user) TableName() string {
  return "user"
}
英文:

To explicitly set a table name, you would have to create an interface Tabler with TableName method, and then create a receiver method (defined in the interface) for the struct:

type user struct {
    ID       int
    Username string `gorm:"size:255"`
    Name     string `gorm:"size:255"`
}

type Tabler interface {
  TableName() string
}

// TableName overrides the table name used by User to `profiles`
func (user) TableName() string {
  return "user"
}

huangapple
  • 本文由 发表于 2017年6月16日 20:16:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/44589060.html
匿名

发表评论

匿名网友

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

确定