Yash Goel
Yash Goel

Reputation: 550

How to set singular name for a table in gorm

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

Upvotes: 39

Views: 37003

Answers (3)

Saurabh
Saurabh

Reputation: 6960

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

Upvotes: 1

bayrinat
bayrinat

Reputation: 1588

Set method TableName for your struct.

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

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

Upvotes: 59

Sivalingam
Sivalingam

Reputation: 931

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,
    },
})

Upvotes: 27

Related Questions