diff --git a/association.go b/association.go index a172e52d..539218bf 100644 --- a/association.go +++ b/association.go @@ -138,7 +138,15 @@ func (association *Association) Replace(values ...interface{}) *Association { return association } -func (association *Association) Clear(value interface{}) *Association { +func (association *Association) Clear() *Association { + relationship := association.Field.Relationship + scope := association.Scope + if relationship.kind == "many_to_many" { + whereSql := fmt.Sprintf("%v.%v = ?", relationship.joinTable, scope.Quote(ToSnake(relationship.foreignKey))) + scope.db.Model("").Table(relationship.joinTable).Where(whereSql, association.PrimaryKey).Delete("") + } else { + association.err(errors.New("clear only support many to many")) + } return association } diff --git a/association_test.go b/association_test.go index ff96a47b..457b2183 100644 --- a/association_test.go +++ b/association_test.go @@ -190,17 +190,19 @@ func TestManyToMany(t *testing.T) { // Replace var languageB Language db.Where("name = ?", "BB").First(&languageB) - db.Debug().Model(&user).Association("Languages").Replace(languageB) + db.Model(&user).Association("Languages").Replace(languageB) if db.Model(&user).Association("Languages").Count() != 1 { - t.Errorf("Relations should be deleted with Delete") + t.Errorf("Relations should be replaced") } db.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}}) if db.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) { - t.Errorf("Relations should be deleted with Delete") + t.Errorf("Relations should be replaced") } - // db.Model(&User{}).Many2Many("Languages").Replace(&[]Language{}) - // db.Model(&User{}).Related(&[]Language{}, "Languages") - // SELECT `languages`.* FROM `languages` INNER JOIN `user_languages` ON `languages`.`id` = `user_languages`.`language_id` WHERE `user_languages`.`user_id` = 111 + // Clear + db.Model(&user).Association("Languages").Clear() + if db.Model(&user).Association("Languages").Count() != 0 { + t.Errorf("Relations should be cleared") + } }