37
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'.

Eklavya
  • 17,618
  • 4
  • 28
  • 57
Yash Goel
  • 530
  • 1
  • 6
  • 15

3 Answers3

50

Set method TableName for your struct.

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

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

Ether
  • 53,118
  • 13
  • 86
  • 159
bayrinat
  • 1,468
  • 8
  • 18
21

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,
    },
})
Ezequiel Muns
  • 7,492
  • 33
  • 57
Sivalingam
  • 841
  • 11
  • 16
0

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"
}
Saurabh
  • 5,176
  • 4
  • 32
  • 46