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'.
GORM provides First , Take , Last methods to retrieve a single object from the database, it adds LIMIT 1 condition when querying the database, and it will return the error ErrRecordNotFound if no record is found.
Set method TableName
for your struct.
func (user) TableName() string { return "user" }
Link: https://gorm.io/docs/models.html#conventions
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, }, })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With