I want to select with gorm and return a specific value of json.

Asked 2 years ago, Updated 2 years ago, 84 views

import(
    "github.com/jinzhu/gorm"
    _"github.com/mattn/go-sqlite3"
)

typeUnivNormalTimeTable structure {
    Id int`json: "id"`
    Hour int `json: "hour"`
    Minute int`json: "minute"`
    DayOfTheWeek string `json: "day_of_the_week"`
}

typeUnivNormalTimeTable[]UnivNormalTimeTable

typeUnivNormalTimeTableRepository structure{}

vardb*gorm.DB
var error

funcinit(){
    db, err=gorm.Open("sqlite3", "data/kamigamo.db")
    if err!=nil{
        panic(err)
    }
    db.AutoMigrate(&UnivNormalTimeTable{})
}

func NewUnivNormalTimeTableRepository()UnivNormalTimeTableRepository{
    returnUnivNormalTimeTableRepository{}
}

func(pUnivNormalTimeTableRepository) LoadKamigamoTime()UnivNormalTimeTable{
    varunivNormalTimeTable=UnivNormalTimeTables{}
    db.Select("hour, minute, day_of_the_week").Find(&univNormalTimeTable)
    return univNormalTimeTable
}

I'm creating a model like the one above, but I don't need to return the id with json, so I'm selecting something other than the id.As a result of calling this, the json is

{
            "id"—0,
            "hour"—9,
            "minute"—5,
            "day_of_the_week": "normal"
        },
        {
            "id"—0,
            "hour"—9,
            "minute"—15,
            "day_of_the_week": "normal"
        },...

It will return in the form shown in , and the id will be zero.I would like to know how to return json excluding id

go gorm

2022-09-30 21:30

1 Answers

Because we use variables of type UnivNormalTimeTables, the return value structure always has the Id field.This field is the current behavior because 0 was substituted when the structure was initialized.For example, you can output JSON without the Id field by changing the code of the part where you are converting a variable of type UnivNormalTimeTables to JSON.Alternatively, you can create a separate structure to store results, such as http://doc.gorm.io/advanced.html#sql-builder.


2022-09-30 21:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.