Home >Backend Development >Golang >How to Scan GORM Query Results into Custom Structures: Public Fields vs. Annotations?
Scanning into a GORM Query Result
When attempting to scan the results of a query into a custom structure, it's important to adhere to GORM's naming conventions to ensure successful mapping.
To resolve the issue of default values, consider the following:
Public Fields with Matching Names:
Create a publicly accessible struct with field names that match the database column names exactly. For example:
<code class="go">type Res struct { ID int Number int UserID int }</code>
Column Mapping with GORM Annotations:
Specify explicit column mappings using GORM annotations. Replace the field names with the actual column names in the database:
<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 adopting either of these approaches, GORM can correctly map the query results to your custom structure. Remember to check that the generated SQL query matches the expected results and refer to GORM's documentation for further guidance on custom struct scanning.
The above is the detailed content of How to Scan GORM Query Results into Custom Structures: Public Fields vs. Annotations?. For more information, please follow other related articles on the PHP Chinese website!