gorm icon indicating copy to clipboard operation
gorm copied to clipboard

Is there a way to delete orphan when update my model ?

Open selfeuse opened this issue 2 years ago • 3 comments

Your Question

Hello, I looked at the doc and issues on github but couldn't find an answer. I've got a recipe model :

type Recipe struct {
	gorm.Model
	Title       string        `json:"title"`
	Quantity    []Quantity    `json:"quantity" gorm:"constraint:OnDelete:CASCADE,OnUpdate:CASCADE;"`
}

That has many Quantity children:

type Quantity struct {
	gorm.Model
	RecipeID     uint
	IngredientID uint
	Ingredient   Ingredient `json:"ingredient"`
	Weight       int     `json:"weight"`
}

that itself has many-to-many relationships:

type Ingredient struct {
	gorm.Model
	Name string `json:"name"`
}

To update it, I'm doing rp.db.Session(&gorm.Session{FullSaveAssociations: true}).Model(&recipe).Where("id = ?", recipe.ID).Updates(&recipe)

It's working well if I'm changing the weight of Quantity, if I add a Quantity element to the array, but not if I'm removing one of them

Example before update:

recipe: {
    ...
    quantity: [
        {
            recipe_id: 1,
           ingredient_id: 1,
           weight: 250
        },
        {
            recipe_id: 1,
            ingredient_id: 2,
            weight: 250
        },
    ]
}

After update, I have the exactly same array, whereas I should have:

recipe: {
    ...
    quantity: [
        {
            recipe_id: 1,
            ingredient_id: 1,
            weight: 250
        }
    ]
}

Does anyone know how I can delete orphan ?

selfeuse avatar Jan 19 '23 20:01 selfeuse

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days

github-actions[bot] avatar Jan 16 '24 02:01 github-actions[bot]

@selfeuse did you figure out how to fix this nicely?

NazariiMed avatar Aug 13 '24 15:08 NazariiMed

@NazariiMed Unfortunately no, but I'm open to any suggestions or ideas you might have !

selfeuse avatar Aug 14 '24 19:08 selfeuse