Your Question

How do I get the column name from the model struct field?

  • Model:
type Animal struct {
  AnimalID int64     `gorm:"column:beast_id"`        
  Birthday time.Time `gorm:"column:day_of_the_beast"`
  Age      int64     `gorm:"column:age_of_the_beast"` 
}
  • I want to get the value of the column tag

The document you expected this should be explained

Expected answer

  • GORM has a method that returns the column name

Comment From: s-takehana

How about this?

package main

import (
    "fmt"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "time"
)

type Animal struct {
    AnimalID int64     `gorm:"column:beast_id"`
    Birthday time.Time `gorm:"column:day_of_the_beast"`
    Age      int64     `gorm:"column:age_of_the_beast"`
}

func main() {
    dsn := "host=postgres user=postgres password=***** dbname=postgres port=5432"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    db.AutoMigrate(&Animal{})

    result, _ := db.Debug().Migrator().ColumnTypes(&Animal{})
    for _, v := range result {
        fmt.Println(v.Name())
    }
}
2021/07/04 12:34:50 /go/pkg/mod/gorm.io/driver/postgres@v1.1.1-0.20210614014255-4c6dc88331ab/migrator.go:68
[0.472ms] [rows:-] SELECT CURRENT_DATABASE()

2021/07/04 12:34:50 /go/pkg/mod/gorm.io/driver/postgres@v1.1.1-0.20210614014255-4c6dc88331ab/migrator.go:302
[9.747ms] [rows:-] SELECT column_name, is_nullable, udt_name, character_maximum_length, numeric_precision, numeric_precision_radix, numeric_scale, datetime_precision FROM information_schema.columns WHERE table_catalog = 'postgres' AND table_schema = CURRENT_SCHEMA() AND table_name = 'animals'
beast_id
day_of_the_beast
age_of_the_beast

Comment From: li-zeyuan

thank you for your help

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 30 days

Comment From: nermolov

Is there any way to map these to the struct field names? Some of my models have fields that are skipped for GORM so directly mapping this array to a field name array from reflect doesn't work.

Comment From: pavelpatrin

@nermolov agree, SELECT * is almost always bad idea, since we already knows which fields struct has. Database schema may have additional column with large amount of data that is not used by a Gorm Model.