When using GORM for database operations, if the field names in the database do not match those in your Go model, or if you need to define specific aliases for certain fields, you can use gorm:"column:alias" to specify this mapping in your model.
For example, suppose you have a database table users with a field named first_name, but in your Go struct model, you want to represent it as FirstName. In this case, you can use the column tag to map the alias:
gotype User struct { gorm.Model FirstName string `gorm:"column:first_name"` LastName string `gorm:"column:last_name"` }
In the above example, the FirstName and LastName fields are mapped to the database columns first_name and last_name.
If you need to read data from the database into these models, GORM automatically handles this field mapping. For instance, when executing a query:
govar user User result := db.First(&user, 1) // query by ID if result.Error != nil { log.Fatalf("Error when fetching data: %v", result.Error) } fmt.Printf("User: %+v", user)
In this query operation, even though the database field names are first_name and last_name, GORM correctly populates the data into the FirstName and LastName fields of the User struct.
This mapping applies not only to queries but also to create and update operations. For example, creating a new user might look like this:
gonewUser := User{FirstName: "Alice", LastName: "Johnson"} result := db.Create(&newUser) if result.Error != nil { log.Fatalf("Failed to create user: %v", result.Error) }
In this example, even though the Go model uses FirstName and LastName, GORM will still insert their values into the first_name and last_name fields.