forked from mirror/gorm
Replace many2many associations with empty
This commit is contained in:
parent
a480621b76
commit
58596afda1
|
@ -139,18 +139,18 @@ 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 {
|
query = query.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
|
||||||
query = query.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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"))
|
||||||
}
|
}
|
||||||
|
|
|
@ -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")
|
||||||
|
|
Loading…
Reference in New Issue