Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a table name from a model in gorm?

Tags:

go

go-gorm

Is it possible to get model's table name? I see that it's possible to get it from ModelStruct but I don't know how to do it correctly. I didn't find any initializations for this structure.

user := User{}
tableName := db...
like image 242
fr05t1k Avatar asked Aug 24 '18 07:08

fr05t1k


People also ask

How do I change the default table name in Gorm?

GORM uses the field with the name ID as the table’s primary key by default. GORM pluralizes struct name to snake_cases as table name, for struct User, its table name is users by convention You can change the default table name by implementing the Tabler interface, for example:

What is the table name of struct in Gorm?

Pluralized Table Name GORM pluralizes struct name to snake_cases as table name, for struct User, its table name is users by convention

How do I retrieve a single object from a Gorm?

Retrieving a single object GORM provides First, Take, Last method to retrieve a single object from the database, it adds LIMIT 1 condition when querying the database, and it will return error ErrRecordNotFound if no record found.

How do I use Gorm for more complicated SQL queries?

For more complicated SQL queries. please also refer to Group Conditions in Advanced Query. Select allows you to specify the fields that you want to retrieve from database. Otherwise, GORM will select all fields by default. ... ... ... You can use Joins eager loading associations with a single SQL, for example:


1 Answers

For Gorm v2, according to https://github.com/go-gorm/gorm/issues/3603, you can do:

stmt := &gorm.Statement{DB: DB}
stmt.Parse(&ColumnStruct2{})
stmt.Schema.Table
like image 77
Aibek Avatar answered Oct 06 '22 06:10

Aibek