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

How can I skip a specific field from struct while inserting with gorm

1个答案

1

When using Gorm for database operations, you may want to exclude certain fields from a struct when inserting data into the database. For example, some fields might represent computed values or temporary data that should not be persisted.

In Gorm, you can skip specific fields by applying Gorm tags to the model struct. Specifically, use the - tag or set gorm:"-" to instruct Gorm to ignore the field during insertion.

Here is a simple example:

go
package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) // Define the model type Product struct { gorm.Model Code string Price uint TemporaryData string `gorm:"-"` } func main() { // Connect to the database db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // Auto-migration mode db.AutoMigrate(&Product{}) // Create a record db.Create(&Product{Code: "D42", Price: 100, TemporaryData: "This won't be saved"}) }

In this example, the TemporaryData field in the Product struct is marked with gorm:"-", so Gorm will not persist it to the database when creating a new record. This approach is especially valuable for fields that should not be saved to the database or are not part of the table schema, enabling precise control over what data is stored.

2024年8月12日 17:27 回复

你的答案