Describe the feature
I want to get the name of the table for an arbitrary struct (that may or may not have a custom naming strategy). For example, the name of the Users table, that doesn't have a TableName function. In v1 I could do tableName := db.NewScope(&User{}).TableName() to get a tableName of users, but that is no longer supported in the current version v2.
I want a function that allows me to get the table name of a struct.
Motivation
I have found a way to do it by running a finaliser:
table_name := db.First(&WantToKnowTheTableForThisStruct{}).Statement.Table
This seems like a bad hack. Running a finaliser seems clunky and unnecessary. I don't want to run a query for items in the table, I just want to know the table name for my variable. Something like:
tableName := db.GetTableName(&MyStructP{})
Related Issues
I asked this question on Stack Overflow but not getting anywhere, other than a suggestion to use the finaliser in dry run mode. https://stackoverflow.com/questions/72976339/get-table-name-from-struct-in-gorm-io
Comment From: twocs
It looks like gorm.Statement provides access to the schema.
func GetSchema(table any) *schema.Schema {
stmt := &gorm.Statement{DB: DB}
stmt.Parse(table)
return stmt.Schema
}
func main() {
tableSchema := GetSchema(MyTable{})
fmt.Println(tableSchema.Table)
}
Gorm Playground link: https://github.com/twocs/playground/tree/tablename