Cannot delete GORM many2many association due to foreign key constraint

41 views Asked by At

I have two models that are exactly like the documentation of GORM:

type User struct {
  gorm.Model
  Languages []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
  gorm.Model
  Name string
}

Where User has an explicit reference to languages, but languages does not have an explicit reference to users. I'm trying to delete a language, and I get:

 ERROR: update or delete on table "languages" violates foreign key constraint "fk_user_languages_language" on table "user_languages" (SQLSTATE 23503)

I have tried several methods, including Select deleting:

db.Select(clause.Associations).Delete(&user)

and using Unscoped(). Absolutely nothing works, I am unable to delete this object. I expect GORM to be able to handle deleting the proper rows in the association table automatically.

Thank you

1

There are 1 answers

2
Alex Pliutau On

The issue you're encountering arises because GORM, by default, attempts to maintain data integrity by enforcing the foreign key constraint between the "languages" and "user_languages" tables. When you try to directly delete a "Language" object, GORM detects that there are still associations present in the "user_languages" table. This foreign key constraint prevents the deletion of the "Language" until the associations are removed.

Explicitly Disassociate Users Before Deletion:

var languageToDelete Language
// ... (fetch the language)

db.Model(&languageToDelete).Association("Users").Clear() // Removes all associations

db.Delete(&languageToDelete)