How to get a table name from a model in gorm?
Asked Answered
R

4

9

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...
Rosalie answered 24/8, 2018 at 7:26 Comment(0)
R
9

Like this:

tableName := db.NewScope(model).GetModelStruct().TableName(db)

Update: Shorter

tableName := db.NewScope(model).TableName() 
Rosalie answered 24/8, 2018 at 7:37 Comment(4)
it could be shorter: tableName := db.NewScope(model).TableName()Leanaleanard
The accepted answer does not work for the library at gorm.ioDelindadelineate
The accepted answer works for v1, for v2 check the answer above.Kohn
db.NewScope doesnt exists.Vanwinkle
A
14

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
Ardithardme answered 16/10, 2020 at 8:1 Comment(0)
R
9

Like this:

tableName := db.NewScope(model).GetModelStruct().TableName(db)

Update: Shorter

tableName := db.NewScope(model).TableName() 
Rosalie answered 24/8, 2018 at 7:37 Comment(4)
it could be shorter: tableName := db.NewScope(model).TableName()Leanaleanard
The accepted answer does not work for the library at gorm.ioDelindadelineate
The accepted answer works for v1, for v2 check the answer above.Kohn
db.NewScope doesnt exists.Vanwinkle
C
5

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)
Costa answered 31/3, 2022 at 21:52 Comment(0)
H
0

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))
}
Hengelo answered 20/12, 2023 at 19:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.