go - 无法更新具有一对多关联的模型
问题描述
我在模型包中有这个结构
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 测试我的端点以更新数据时,订单表已成功更新。但不在数据库的项目表中。任何人都可以帮助我吗?
解决方案
在此链接(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
我还没有能够测试它,所以我不知道它是否有效。对不起我的英语不好。
问候
推荐阅读
- c++ - 如何计算一个循环执行了多少次?
- c++ - 在 C++ 中,有没有办法在不发生移动或复制的情况下将值传递给构造函数?
- html - 如何删除我的网站的左白边框颜色
- python - {} 和 format 在这个命令 python 中做了什么?
- java - 使用 switch 语句在 Java 中解耦的问题
- php - DigitalOcean Spaces:无法将文件设置为公开
- r - R中列的条件总和
- python - Kivy:相机不尊重 pos_hint(但尊重 size_hint)
- sql-server - 有人可以解释这个 DROP TABLE 命令吗?我错过了什么?
- c++ - std::initializer_list 作为模板类中的构造函数参数