When using GORM, retrieving field values from models can be accomplished through multiple approaches. GORM is a widely adopted ORM library for the Go programming language, designed for database operations. Below are common methods to retrieve field values:
1. Directly Accessing Fields via Struct
The most straightforward method involves accessing values directly through fields defined in the struct after database querying. This requires you to first define a model and ensure the fields are populated from the database during the query.
gotype Product struct { gorm.Model Code string Price uint } // Query example var product Product result := db.First(&product, "code = ?", "D42") // Assume db is *gorm.DB instance if result.Error != nil { log.Fatalf("Query failed: %v", result.Error) } fmt.Println(product.Price) // Directly access Price field
2. Using the Pluck Method
If you need to extract only a single field's value from the database, the Pluck method is efficient for retrieving the specified column.
govar prices []uint result := db.Model(&Product{}).Where("code = ?", "D42").Pluck("price", &prices) if result.Error != nil { log.Fatalf("Query failed: %v", result.Error) } fmt.Println(prices) // Output all prices matching the query
3. Using the Scan Method
To scan query results into different structs or variables, use the Scan method. This is particularly useful for complex association queries or when only partial fields are required.
gotype Result struct { Price uint } var resultData Result result := db.Model(&Product{}).Select("price").Where("code = ?", "D42").Scan(&resultData) if result.Error != nil { log.Fatalf("Query failed: %v", result.Error) } fmt.Println(resultData.Price)
4. Using Raw SQL
In cases where raw SQL is more intuitive or necessary for specific database optimizations, GORM allows executing raw SQL and mapping results to models or arbitrary structs.
govar price uint result := db.Raw("SELECT price FROM products WHERE code = ?", "D42").Scan(&price) if result.Error != nil { log.Fatalf("Query failed: %v", result.Error) } fmt.Println(price)
These methods can be selected based on specific application scenarios and requirements. During interviews, you can demonstrate your understanding and flexibility with GORM operations by addressing specific questions.