Search code examples
gogo-gormgo-gin

Can't update model that have one to many association


I have this struct in model package

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"`
}

Then i make handler for update the data:

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)
}

When i'm trying to use Postman for test my endpoint to update data, order table is successfully updated. But not in item table in database. Anyone can help me please?


Solution

  • In this link (https://github.com/go-gorm/gorm/issues/3487) they have the same problem and they specify that in a recent version of GORM it was no longer possible with Save() to update the relations.

    But later it is mentioned that they made a change and it would be possible this way:

    DB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&order)
    

    https://github.com/go-gorm/gorm/issues/3487#issuecomment-698303344

    I haven't been able to test it yet, so I don't know if it works well. Sorry for my English.

    Regards