How to Match GORM Struct Fields with Query Column Names?

Mary-Kate Olsen
Release: 2024-10-26 05:39:02
Original
608 people have browsed it

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

  • Ensure that your struct fields are public and use the same names as the column names in the query result. For example:
<code class="go">type Res struct {
    ID     int
    Number int
    UserID int
}</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!