【问题标题】:"reflect: Field index out of range" panic on update“反映:字段索引超出范围”更新时出现恐慌
【发布时间】:2020-12-01 04:25:36
【问题描述】:

我在使用 Gorm 实施基本更新时感到恐慌,但我找不到任何有关它的信息。按照 Gorm 的文档,我看起来并没有做错事。

module achiever

go 1.15

require (
    gorm.io/driver/postgres v1.0.5
    gorm.io/gorm v1.20.7
)
type Task struct {
    ID    uint   `json:"id" gorm:"primary_key"`
    Title string `json:"title"`
}

type UpdateTaskInput struct {
    Title string `json:"title"`
}

func UpdateTask(id uint, input UpdateTaskInput) bool {
    var task Task
    if err := models.DB.Where("id = ?", id).First(&task).Error; err != nil {
        return false
    }

    models.DB.Model(&task).Updates(input)

    return true
}
reflect: Field index out of range
/usr/local/go/src/reflect/value.go:854 (0x4bf758)
    Value.Field: panic("reflect: Field index out of range")
/home/raphael/gows/pkg/mod/gorm.io/gorm@v1.20.7/schema/field.go:388 (0x57b984)
    (*Field).setupValuerAndSetter.func1: fieldValue := reflect.Indirect(value).Field(field.StructField.Index[0])
/home/raphael/gows/pkg/mod/gorm.io/gorm@v1.20.7/callbacks/update.go:230 (0x881670)
    ConvertToAssignments: value, isZero := field.ValueOf(updatingValue)
/home/raphael/gows/pkg/mod/gorm.io/gorm@v1.20.7/callbacks/update.go:64 (0x87f259)
    Update: if set := ConvertToAssignments(db.Statement); len(set) != 0 {
/home/raphael/gows/pkg/mod/gorm.io/gorm@v1.20.7/callbacks.go:105 (0x5a65bc)
    (*processor).Execute: f(db)
/home/raphael/gows/pkg/mod/gorm.io/gorm@v1.20.7/finisher_api.go:303 (0x5ae2c6)
    (*DB).Updates: tx.callbacks.Update().Execute(tx)
/home/raphael/ws/achiever/server/controllers/tasks.go:74 (0xad62cd)
    UpdateTask: models.DB.Model(&task).Updates(input)

我不知道错误来自哪里。

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    正如 jugendhacker 所说,我遇到了同样的问题:您需要在更新函数中构建模型的结构:

    models.DB.Model(&task).Updates(&Task{Title: input.Title})
    

    这在GORM docs 中有说明,如果您正在构建 API,将其作为 PUT 方法实现会更合适,因为您传递的是新对象而不是修补现有对象。

    【讨论】:

      【解决方案2】:

      将ID 字段添加到UpdateTaskInput 结构可以解决此问题

      type UpdateTaskInput struct {
          ID uint `json:"-"`
          Title string `json:"title"`
      }
      

      【讨论】:

        【解决方案3】:

        据我所知,更新不支持“智能选择字段”,因此您需要先构造原始结构。

        models.DB.Model(&task).Updates(&Task{Title: input.Title})
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-12
          • 1970-01-01
          • 2014-11-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-31
          相关资源
          最近更新 更多