亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅在更新時出現 Gorm 和 Gin 錯誤 500

僅在更新時出現 Gorm 和 Gin 錯誤 500

Go
HUX布斯 2022-07-11 17:39:19
我有一個非常簡單的任務列表 CRUD,到目前為止,我能夠創建、列出所有、按 ID 列出和刪除記錄,但是當我嘗試更新時,它給了我以下錯誤:go-proj          | reflect: call of reflect.Value.Field on string Valuego-proj          | /usr/local/go/src/reflect/value.go:850 (0x4a2464)go-proj          |      Value.Field: panic(&ValueError{"reflect.Value.Field", v.kind()})go-proj          | /go/pkg/mod/gorm.io/[email protected]/schema/field.go:393 (0x996e50)go-proj          |      (*Field).setupValuerAndSetter.func2: fieldValue := reflect.Indirect(value).Field(field.StructField.Index[0]).Field(field.StructField.Index[1])go-proj          | /go/pkg/mod/gorm.io/[email protected]/callbacks/update.go:230 (0xb3e3f0)go-proj          |      ConvertToAssignments: value, isZero := field.ValueOf(updatingValue)go-proj          | /go/pkg/mod/gorm.io/[email protected]/callbacks/update.go:64 (0xb3bfd9)go-proj          |      Update: if set := ConvertToAssignments(db.Statement); len(set) != 0 {go-proj          | /go/pkg/mod/gorm.io/[email protected]/callbacks.go:105 (0x9a5b7c)go-proj          |      (*processor).Execute: f(db)go-proj          | /go/pkg/mod/gorm.io/[email protected]/finisher_api.go:303 (0x9ad886)我嘗試過更改Gorm和Gin框架的版本
查看完整描述

2 回答

?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

好吧,這是一種解決方法,可能我會在Gorm 的 Github上打開一個問題,因為我認為這不是正確的做法,我唯一要做的就是從使用反射UpdateListInput struct的變量轉換包裹map[string]interface{}


這是我的控制器:


func Update(c *gin.Context) {

        var list models.List

        if err := models.DB.Where("id = ?", c.Param("id")).First(&list).Error; err != nil {

                c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found"})

                return

        }


        var input UpdateListInput

        if err := c.ShouldBindJSON(&input); err != nil {

                c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})

                return

        }

        v := reflect.ValueOf(input)

        typeOfV := v.Type()


        inputData := map[string]interface{}{}


        for i := 0; i < v.NumField(); i++ {

                inputData[typeOfV.Field(i).Name] = v.Field(i).Interface()

        }


        if err := models.DB.Model(&list).Updates(inputData).Error; err != nil {

                c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})

                return

        }


        c.JSON(http.StatusOK, gin.H{"data": list})

}


查看完整回答
反對 回復 2022-07-11
?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

在控制器中試試這個:


data := models.List{Title: input.Title,Status: input.Status}


if err := models.DB.Model(&list).Updates(&data).Error; err != nil {

        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})

}


c.JSON(http.StatusOK, gin.H{"data": data})



查看完整回答
反對 回復 2022-07-11
  • 2 回答
  • 0 關注
  • 302 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號