Replace many2many associations with empty

This commit is contained in:
Jinzhu 2015-09-30 21:30:58 +08:00
parent a480621b76
commit 58596afda1
2 changed files with 12 additions and 7 deletions

View File

@ -139,7 +139,6 @@ func (association *Association) Replace(values ...interface{}) *Association {
addedPrimaryKeys = append(addedPrimaryKeys, primaryKey) addedPrimaryKeys = append(addedPrimaryKeys, primaryKey)
} }
if len(addedPrimaryKeys) > 0 {
query := scope.NewDB() query := scope.NewDB()
for idx, foreignKey := range relationship.ForeignDBNames { for idx, foreignKey := range relationship.ForeignDBNames {
if field, ok := scope.FieldByName(relationship.ForeignFieldNames[idx]); ok { if field, ok := scope.FieldByName(relationship.ForeignFieldNames[idx]); ok {
@ -147,10 +146,11 @@ func (association *Association) Replace(values ...interface{}) *Association {
} }
} }
if len(addedPrimaryKeys) > 0 {
sql := fmt.Sprintf("%v NOT IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(addedPrimaryKeys)) sql := fmt.Sprintf("%v NOT IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(addedPrimaryKeys))
query = query.Where(sql, toQueryValues(addedPrimaryKeys)...) query = query.Where(sql, toQueryValues(addedPrimaryKeys)...)
association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, query, relationship))
} }
association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, query, relationship))
} else { } else {
association.setErr(errors.New("replace only support many to many")) association.setErr(errors.New("replace only support many to many"))
} }

View File

@ -211,6 +211,11 @@ func TestManyToMany(t *testing.T) {
t.Errorf("Relations should be replaced") t.Errorf("Relations should be replaced")
} }
DB.Model(&user).Association("Languages").Replace()
if len(user.Languages) != 0 || DB.Model(&user).Association("Languages").Count() != 0 {
t.Errorf("Relations should be replaced with empty")
}
DB.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}}) DB.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}})
if len(user.Languages) != 2 || DB.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) { if len(user.Languages) != 2 || DB.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) {
t.Errorf("Relations should be replaced") t.Errorf("Relations should be replaced")