Home > Mobile >  Gorm get column name
Gorm get column name

Time:07-20

I have the following model in gorm

type Person struct {
    ID        uuid.UUID      `gorm:"type:uuid;default:uuid_generate_v4()" json:"id"`
    Name      string         `gorm:"not null,type:text" json:"name"`
    CreatedAt time.Time      `gorm:"autoCreateTime" json:"created_at"`
    UpdatedAt time.Time      `gorm:"autoUpdateTime" json:"updated_at"`
    DeletedAt gorm.DeletedAt `gorm:"index,->" json:"-"`
}

Currently, I am getting the field name using the reflect package. However, I am getting the name of the field on JSON.

field, _ := reflect.TypeOf(&Person{}).Elem().FieldByName("CreatedAt")
tag := field.Tag.Get("json") // tag is created_at

Is it possible to get the column name using gorm?

CodePudding user response:

Possible solution

The solution is to retrieve («parse») the schema from the model (please, note: from the model — not from the database).

References

Draft example program

go.mod

module gorm/example

go 1.18

require (
    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.sum

github.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=

Program (main.go)

package main

import (
    "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 create schema")
    }

    m := make(map[string]string)
    for _, field := range s.Fields {
        dbName := field.DBName
        modelName := field.Name
        m[modelName] = dbName
    }

    fmt.Println("Model to database field name map:", m)
    fmt.Println("CreatedAt field is mapped to", m["CreatedAt"], "column")
}

Build

$ go build main.go

Run

$ ./main

Output

Model to database 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

CodePudding user response:

use tag like this:

gorm:"column:uid"

type UserInfo struct {
    Uid       int       `json:"uid" gorm:"column:uid" form:"uid"` 
    Uname     string    `json:"uname" gorm:"column:uname" form:"uname"`
}
  • Related