Gorm 获取列名

我在 gorm 中有以下模型


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,->"`

}

是否可以获取列名?我想要 gorm 将生成的列名


HUWWW
浏览 312回答 2
2回答

守候你守候我

可能的解决方案解决方案是从模型中检索(«解析»)模式。请注意:来自模型——而不是来自“物理”数据库。参考如何获取结构/模型字段和数据库列的 map[string]string?· 问题 #5114 · go-gorm/gorm。解决方案评论:tzinckgraf于 3 月 4 日发表评论。如何从模型结构字段中获取列名·问题#4497·go-gorm/gorm。稍微相关的问题。go - 如何从 gorm 中的模型中获取表名?- 堆栈溢出。示例程序草稿go.modmodule gorm/examplego 1.18require (    github.com/google/uuid v1.3.0    gorm.io/gorm v1.23.8)require (    github.com/jinzhu/inflection v1.0.0 // indirect    github.com/jinzhu/now v1.1.4 // indirect)go.sumgithub.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas=github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=gorm.io/gorm v1.23.8 h1:h8sGJ+biDgBA1AD1Ha9gFCx7h8npU7AsLdlkX0n2TpE=gorm.io/gorm v1.23.8/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=程序 ( main.go)package mainimport (    "fmt"    "github.com/google/uuid"    "gorm.io/gorm"    "gorm.io/gorm/schema"    "sync"    "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() {    s, err := schema.Parse(&Person{}, &sync.Map{}, schema.NamingStrategy{})    if err != nil {        panic("failed to parse schema")    }    m := make(map[string]string)    for _, field := range s.Fields {        dbName := field.DBName        modelName := field.Name        m[modelName] = dbName    }    fmt.Println("Model to schema field name map:", m)    fmt.Println("CreatedAt field is mapped to", m["CreatedAt"], "column")}建造$ go build main.go跑步$ ./main输出Model to schema field name map: map[CreatedAt:created_at DeletedAt:deleted_at ID:id Name:name UpdatedAt:updated_at]CreatedAt field is mapped to created_at column

牧羊人nacy

使用这样的标签:gorm:“列:uid”type UserInfo struct {    Uid       int       `json:"uid" gorm:"column:uid" form:"uid"`     Uname     string    `json:"uname" gorm:"column:uname" form:"uname"`}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go