Struct Field Naming in GORM Query Scanning
When attempting to scan the results of a query into a custom GORM struct, it's crucial to note the convention GORM employs for field naming. By default, GORM expects the struct fields to match the column names in the query result.
To resolve the default value issue you're encountering, try the following approaches:
Option 1: Public Fields and Proper Naming
type Res struct {
ID int
Number int
UserID int
}
Option 2: Custom Column Mappings
Alternatively, you can specify explicit column mappings using the gorm:"column" tag on each field. This allows you to define a different name for the field while retaining the original column name in the query result. For example:
type res struct {
id int `gorm:"column:id"`
number int `gorm:"column:number"`
user_id int `gorm:"column:user_id"`
}
By implementing one of these options, you should be able to successfully scan the query results into your custom GORM struct.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3