乐闻世界logo
搜索文章和话题

How do I get column names and values from a gorm object?

1个答案

1

When using GORM, if you want to retrieve column names and their corresponding values from a model object, there are several methods to achieve this. I will introduce them separately and provide specific examples.

Method 1: Using Reflection

In Go, reflection can be used to dynamically obtain information about an object. By leveraging reflection, you can iterate through the fields of the model to extract the database column names and their values.

Example Code:

go
package main import ( "fmt" "reflect" "gorm.io/gorm" ) type User struct { gorm.Model Name string Age int } func GetFieldsAndValues(model interface{}) map[string]interface{} { result := make(map[string]interface{}) t := reflect.TypeOf(model) v := reflect.ValueOf(model) for i := 0; i < t.NumField(); i++ { field := t.Field(i) // Use the GORM tag to obtain the corresponding database column name columnName := field.Tag.Get("column") // Optimized: GORM tags typically use "column" for direct access // Retrieve the value value := v.Field(i).Interface() result[columnName] = value } return result } func main() { user := User{Name: "John Doe", Age: 30} fieldsValues := GetFieldsAndValues(user) fmt.Println(fieldsValues) }

In this example, the GetFieldsAndValues function accepts any model type, uses reflection to retrieve the database column names and values for each field, and returns a map.

Method 2: Using GORM's Schema Interface

GORM provides a Schema interface that allows direct retrieval of model information, including column names.

Example Code:

go
package main import ( "fmt" "gorm.io/gorm" "gorm.io/driver/sqlite" ) type User struct { gorm.Model Name string Age int } func main() { db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Auto-migrate the schema db.AutoMigrate(&User{}) // Create instance user := User{Name: "John Doe", Age: 30} db.Create(&user) // Retrieve Schema information stmt := &gorm.Statement{DB: db} stmt.Parse(&User{}) for _, field := range stmt.Schema.Fields { fmt.Println("Column Name:", field.DBName, "Value:", field.ReflectValueOf(reflect.ValueOf(user)).Interface()) } }

In this example, we first define a User struct, then use GORM to open the database and auto-migrate the schema. By creating a statement and parsing the model, we can retrieve the database column names and current instance values for all fields.

Both methods can be used in GORM to retrieve model column names and values, and the choice depends on specific requirements and scenarios.

2024年8月12日 18:44 回复

你的答案