无法更新具有一对多关联的模型
Can't update model that have one to many association
我在模型包中有这个结构
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 table 已成功更新。但不在数据库中的 item table 中。有人可以帮我吗?
在这个 link (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
我还没来得及测试,不知道好不好用。对不起我的英语。
此致
我在模型包中有这个结构
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 table 已成功更新。但不在数据库中的 item table 中。有人可以帮我吗?
在这个 link (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
我还没来得及测试,不知道好不好用。对不起我的英语。
此致