forked from mirror/gorm
Replace many2many associations with empty
This commit is contained in:
parent
a480621b76
commit
58596afda1
|
@ -139,7 +139,6 @@ func (association *Association) Replace(values ...interface{}) *Association {
|
|||
addedPrimaryKeys = append(addedPrimaryKeys, primaryKey)
|
||||
}
|
||||
|
||||
if len(addedPrimaryKeys) > 0 {
|
||||
query := scope.NewDB()
|
||||
for idx, foreignKey := range relationship.ForeignDBNames {
|
||||
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))
|
||||
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 {
|
||||
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")
|
||||
}
|
||||
|
||||
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"}})
|
||||
if len(user.Languages) != 2 || DB.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) {
|
||||
t.Errorf("Relations should be replaced")
|
||||
|
|
Loading…
Reference in New Issue