为了账号安全,请及时绑定邮箱和手机立即绑定

reflect:调用 reflect.Value.SetString on uint Value

reflect:调用 reflect.Value.SetString on uint Value

Go
慕姐4208626 2022-12-19 17:57:41
我正在尝试使用 Golang、Gin 和 GORM 构建一个简单的 CRUD 博客。但是,当我想更新博客内容时,触发了以下错误:reflect: call of reflect.Value.SetString on uint Value/usr/local/go/src/reflect/value.go:223 (0x10bfb25)        flag.mustBe: panic(&ValueError{methodName(), f.kind()})/usr/local/go/src/reflect/value.go:2292 (0x10bfaa3)        Value.SetString: v.mustBe(String)/Users/sam/go/pkg/mod/gorm.io/gorm@v1.23.5/schema/field.go:771 (0x144fcfc)        (*Field).setupValuerAndSetter.func11: field.ReflectValueOf(ctx, value).SetString(data)/Users/sam/go/pkg/mod/gorm.io/gorm@v1.23.5/callbacks/update.go:144 (0x14b7d9a)        ConvertToAssignments.func2: field.Set(stmt.Context, stmt.ReflectValue, value)/Users/sam/go/pkg/mod/gorm.io/gorm@v1.23.5/callbacks/update.go:275 (0x14b62fa)        ConvertToAssignments: assignValue(field, value)/Users/sam/go/pkg/mod/gorm.io/gorm@v1.23.5/callbacks/update.go:73 (0x14b4fe4)        Update.func1: if set := ConvertToAssignments(db.Statement); len(set) != 0 {/Users/sam/go/pkg/mod/gorm.io/gorm@v1.23.5/callbacks.go:130 (0x146d632)        (*processor).Execute: f(db)/Users/sam/go/pkg/mod/gorm.io/gorm@v1.23.5/finisher_api.go:372 (0x1476811)        (*DB).Updates: return tx.callbacks.Update().Execute(tx)/Volumes/Data/Develop/Go/go-blog/controllers/blog.go:65 (0x1693364)        UpdateBlog: models.DB.Model(&blog).Updates(input)/Users/sam/go/pkg/mod/github.com/gin-gonic/gin@v1.7.7/context.go:168 (0x168a121)        (*Context).Next: c.handlers[c.index](c)/Users/sam/go/pkg/mod/github.com/gin-gonic/gin@v1.7.7/recovery.go:99 (0x168a10c)        CustomRecoveryWithWriter.func1: c.Next()/Users/sam/go/pkg/mod/github.com/gin-gonic/gin@v1.7.7/context.go:168 (0x1689246)
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

这可能是因为您使用的结构不同于 models.Blog 来更新。您可以尝试以下操作吗:


func UpdateBlog(c *gin.Context) {

    var blog models.Blog

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

        c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "record not found"})

        return

    }


    var input UpdateBlogInput


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

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

        return

    }


    updateBlog := models.Blog{Title: input.Title, Content: input.Content}


    models.DB.Model(&blog).Updates(&updateBlog)

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

}


查看完整回答
反对 回复 2022-12-19
  • 1 回答
  • 0 关注
  • 373 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号