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

Association Deletion is not working as expected. #7308

Open
AmitKarnam opened this issue Dec 6, 2024 · 0 comments
Open

Association Deletion is not working as expected. #7308

AmitKarnam opened this issue Dec 6, 2024 · 0 comments
Assignees
Labels
type:question general questions

Comments

@AmitKarnam
Copy link

Your Question

I have models as follows,

type MuscleGroup struct {
	gorm.Model         // Embedding gorm.Model
	MuscleGroup string `json:"muscle_group"`
	Description string `json:"description"`
}
type Exercise struct {
	gorm.Model                // Embedding gorm.Model
	Name          string      `json:"name"`
	Description   string      `json:"description"`
	MuscleGroupID uint        `json:"muscle_group_id"`                                                                      // Foreign key for MuscleGroup
	MuscleGroup   MuscleGroup `gorm:"foreignKey:MuscleGroupID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"` // Association
}

Now I have an endpoint to delete a particular musclegroup, since my models follow a has-one relationship, When I delete a muscle group, I need the exercises using this muscle group as reference to be deleted. I've gone though the docs on soft delete and using select statement during delete. I added the clause.Associations now , but still the record for the exercise is present in the database. The referencing muscle group data shows empty when I query the exercise, but the muscle group is present. I was expecting the associated exercise to undergo a soft delete. Delete Query

	// Delete the muscle group from the database
	if err := dbConn.Select(clause.Associations).Delete(&muscleGroup).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "error deleting muscle group"})
		return
	}

##Related Issue I've gone through
#3702

The document you expected this should be explained

  1. https://gorm.io/docs/associations.html#Delete-with-Select
  2. https://gorm.io/docs/delete.html

Expected answer

How can I delete the associated records in exercise table as a part of cascade delete , when I delete the muscle group.

@AmitKarnam AmitKarnam added the type:question general questions label Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question general questions
Projects
None yet
Development

No branches or pull requests

2 participants