如何获取Gorm根据模型生成的数据库列名?
获取Gorm模型对应的数据库列名方法
当然可以获取Gorm为模型生成的数据库列名,以下是两种实用方法:
方法一:通过Migrator获取数据库实际列信息
这种方法需要连接数据库,能拿到数据库中已存在的列的完整信息(包括列名、类型、约束等),代码示例:
package main import ( "gorm.io/driver/postgres" "gorm.io/gorm" "github.com/google/uuid" "time" ) type Person struct { ID uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4()"` Name string `gorm:"not null,type:text"` CreatedAt time.Time `gorm:"autoCreateTime"` UpdatedAt time.Time `gorm:"autoUpdateTime"` DeletedAt gorm.DeletedAt `gorm:"index,->"` } func main() { // 替换为你的数据库DSN dsn := "host=localhost user=postgres password=postgres dbname=test port=5432 sslmode=disable" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { panic(err) } // 获取Person模型对应的列类型信息 columnTypes, err := db.Migrator().ColumnTypes(&Person{}) if err != nil { panic(err) } // 遍历输出列名 for _, colType := range columnTypes { println("列名:", colType.Name()) } }
方法二:直接解析模型Schema(无需连接数据库)
如果只是想提前确认Gorm会生成的列名,不需要连接数据库,直接解析模型的Schema即可:
package main import ( "gorm.io/gorm" "gorm.io/gorm/schema" "github.com/google/uuid" "time" ) type Person struct { ID uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4()"` Name string `gorm:"not null,type:text"` CreatedAt time.Time `gorm:"autoCreateTime"` UpdatedAt time.Time `gorm:"autoUpdateTime"` DeletedAt gorm.DeletedAt `gorm:"index,->"` } func main() { // 解析Person模型的Schema sch, err := schema.Parse(&Person{}, &schema.Config{}, &gorm.DB{}) if err != nil { panic(err) } // 遍历输出每个字段对应的数据库列名 for _, field := range sch.Fields { println("模型字段:", field.Name, "→ 数据库列名:", field.DBName) } }
运行第二种方法后,你会得到如下输出(符合Gorm默认的下划线命名规则):
模型字段: ID → 数据库列名: id 模型字段: Name → 数据库列名: name 模型字段: CreatedAt → 数据库列名: created_at 模型字段: UpdatedAt → 数据库列名: updated_at 模型字段: DeletedAt → 数据库列名: deleted_at
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

