diff --git a/association.go b/association.go index 69be0d01..bb692163 100644 --- a/association.go +++ b/association.go @@ -97,8 +97,12 @@ func (association *Association) Delete(values ...interface{}) *Association { relationship := association.Field.Relationship // many to many if relationship.Kind == "many_to_many" { - whereSql := fmt.Sprintf("%v.%v IN (?)", relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.AssociationForeignKey))) - association.Scope.db.Model("").Table(relationship.JoinTable).Where(whereSql, primaryKeys).Delete("") + whereSql := fmt.Sprintf("%v.%v = ? AND %v.%v IN (?)", + relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.ForeignKey)), + relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.AssociationForeignKey))) + + association.Scope.db.Model("").Table(relationship.JoinTable). + Where(whereSql, association.PrimaryKey, primaryKeys).Delete("") } else { association.err(errors.New("delete only support many to many")) } diff --git a/association_test.go b/association_test.go index a09ab31d..f2873da8 100644 --- a/association_test.go +++ b/association_test.go @@ -1,6 +1,7 @@ package gorm_test import "testing" + import "github.com/jinzhu/gorm" type Cat struct { @@ -207,11 +208,19 @@ func TestManyToMany(t *testing.T) { languages = []Language{} DB.Where("name IN (?)", []string{"CC", "DD"}).Find(&languages) + + user2 := User{Name: "Many2Many_User2", Languages: languages} + DB.Save(&user2) + DB.Model(&user).Association("Languages").Delete(languages, &languages) if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-3 { t.Errorf("Relations should be deleted with Delete") } + if DB.Model(&user2).Association("Languages").Count() == 0 { + t.Errorf("Other user's relations should not be deleted") + } + // Replace var languageB Language DB.Where("name = ?", "BB").First(&languageB)