首页 > 解决方案 > 无法更新具有一对多关联的模型

问题描述

我在模型包中有这个结构

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 测试我的端点以更新数据时,订单表已成功更新。但不在数据库的项目表中。任何人都可以帮助我吗?

标签: gogo-gormgo-gin

解决方案


在此链接(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

我还没有能够测试它,所以我不知道它是否有效。对不起我的英语不好。

问候


推荐阅读