Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
selfeuse opened this issue Jan 19, 2023 · 3 comments
Open

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

selfeuse opened this issue Jan 19, 2023 · 3 comments
Assignees
Labels

Comments

@selfeuse
Copy link

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 selfeuse added the type:question general questions label Jan 19, 2023
Copy link

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

@NazariiMed
Copy link

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

@selfeuse
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants