[GORM] Updating record with its associations

Hello Gophers.

This is my entity:

type DishEntity struct {
	gorm.Model
	Date        time.Time
	Ingredients []MeasuredIngredientEntity `gorm:"many2many:dish_measuredingredient;"`
}

This is my update function:

func UpdateDish(db *gorm.DB, d entities.DishEntity) error {
	if err := db.Updates(&d).Error; err != nil {
		return err
	}
	return nil
}

Here is my problem:

When I add new ingredient to the dish it works as expected but when I remove something the change isn’t reflected in the database.

I know this is not how I suppose to do it but which strategy should I choose then ?

GPT gave me multiple solutions but all of them had some bugs and unexpected behaviors.

Have you tried with Replace?

Have you tried with Replace?

Yes. It didn’t work.

I solved my problem by completely changing my approach. Instead of trying to update the day with ingredients in a single query, I created a separate repository for ingredients only, which takes the dayID as a parameter in its functions.

This topic can be closed.