Reputation: 550
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
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
Reputation: 1588
Set method TableName
for your struct.
func (user) TableName() string {
return "user"
}
Link: https://gorm.io/docs/models.html#conventions
Upvotes: 59
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