【发布时间】: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 表中。谁能帮帮我?
【问题讨论】: