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...
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 this:
tableName := db.NewScope(model).GetModelStruct().TableName(db)
Update: Shorter
tableName := db.NewScope(model).TableName()
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 this:
tableName := db.NewScope(model).GetModelStruct().TableName(db)
Update: Shorter
tableName := db.NewScope(model).TableName()
tableName := db.NewScope(model).TableName()
–
Leanaleanard Another method for Gorm v2, without passing a DB object.
type WeatherStation struct{}
s, _ := schema.Parse(&WeatherStation{}, &sync.Map{}, schema.NamingStrategy{})
fmt.Println(s.Table)
I was facing issue to find table name when trying to setup a scope where two tables can have the same column name. Below snippet works for me.
func(db *gorm.DB) *gorm.DB {
if db.Statement.Model == nil {
return db.WithContext(ctx).Where("deleted_at IS NULL")
}
model := db.Statement.Model
db.Statement.Parse(model)
tableName := db.Statement.Schema.Table
return db.WithContext(ctx).Where(fmt.Sprintf("%s.deleted_at IS NULL", tableName))
}
© 2022 - 2025 — McMap. All rights reserved.
tableName := db.NewScope(model).TableName()
– Leanaleanard