登录
首页 >  Golang >  Go问答

更新拥有一对多关联的模型时遇到困难

来源:stackoverflow

时间:2024-03-12 21:18:26 410浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《更新拥有一对多关联的模型时遇到困难》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我在模型包中有这个结构

type item struct {
    lineitemid  uint   `json:"lineitemid" gorm:"primarykey"`
    itemcode    string `json:"itemcode"`
    description string `json:"description"`
    quantity    int    `json:"quantity"`
    orderid     int    `json:"-"`
}

type order struct {
    orderid      uint      `json:"orderid" gorm:"primarykey"`
    customername string    `json:"customername"`
    orderedat    time.time `json:"orderedat"`
    items        []item    `json:"items" gorm:"foreignkey:orderid"`
}

然后我创建处理程序来更新数据:

func UpdateOrderById(c *gin.Context) {
    id := c.Params.ByName("id")

    var order models.Order

    if err := config.DB.Preload("Items").First(&order, id).Error; err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
        return
    }

    c.ShouldBindJSON(&order)

    if err := config.DB.Save(&order).Error; err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "Record can't update!"})
        return
    }

    c.JSON(http.StatusOK, order)
}

当我尝试使用 postman 测试我的端点以更新数据时,订单表已成功更新。但不在数据库的 item 表中。有人可以帮我吗?


解决方案


在此链接 (https://github.com/go-gorm/gorm/issues/3487) 中,他们遇到了相同的问题,并指出在最新版本的 gorm 中,不再可能使用 save() 来更新关系。

但后来有人提到他们做了改变,这样就有可能:

DB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&order)

https://github.com/go-gorm/gorm/issues/3487#issuecomment-698303344

我还没来得及测试,所以我不知道它是否有效。对不起我的英语。

问候

以上就是《更新拥有一对多关联的模型时遇到困难》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>