Home >Backend Development >Golang >How to Match GORM Struct Fields with Query Column Names?

How to Match GORM Struct Fields with Query Column Names?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 05:39:02691browse

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>

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!

Statement:
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