Home >Backend Development >Golang >How to Match GORM Struct Fields with Query Column Names?
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
<code class="go">type Res struct { ID int Number int UserID int }</code>
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:
<code class="go">type res struct { id int `gorm:"column:id"` number int `gorm:"column:number"` user_id int `gorm:"column:user_id"` }</code>
By implementing one of these options, you should be able to successfully scan the query results into your custom GORM struct.
The above is the detailed content of How to Match GORM Struct Fields with Query Column Names?. For more information, please follow other related articles on the PHP Chinese website!