【问题标题】:Can't update model that have one to many association无法更新具有一对多关联的模型
【发布时间】:2021-05-25 23:05:44
【问题描述】:

我在模型包中有这个结构

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 测试我的端点以更新数据时,order 表已成功更新。但不在数据库中的 item 表中。谁能帮帮我?

【问题讨论】:

    标签: go go-gorm go-gin


    【解决方案1】:

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

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

    问候

    【讨论】:

    • 效果很好,非常感谢@gcamps
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多