Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set singular name for a table in gorm

Tags:

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

like image 359
Yash Goel Avatar asked Jun 16 '17 12:06

Yash Goel


People also ask

What does Gorm model do?

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.


2 Answers

Set method TableName for your struct.

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

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

like image 86
bayrinat Avatar answered Sep 23 '22 01:09

bayrinat


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,     }, }) 
like image 28
Sivalingam Avatar answered Sep 21 '22 01:09

Sivalingam