Retrieving Query Results into a Struct Using gorm
When attempting to scan the results of a query into a struct, it's crucial to adhere to gorm's naming conventions to ensure proper field mapping. If the query results in default values or an empty array, consider the following options:
Public Struct Fields:
Ensure that the res struct has public fields. The struct definition should look like the following:
type res struct { ID int Number int UserID int }
Column Mapping:
Alternatively, explicitly specify the mapping between query columns and struct fields using gorm tags:
type res struct { id int `gorm:"column:id"` number int `gorm:"column:number"` user_id int `gorm:"column:user_id"` }
By following either of these approaches, gorm can correctly map the query results to the fields in the res struct, allowing you to access the results as expected.
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