Extract HandleNormalManyToMany logic with comment.
@@ -444,6 +444,17 @@ func HandleManyToMany(context *qor.Context, scope *gorm.Scope, meta *Meta, recor
if fieldHasVersion && metaValue.Value != nil && compositePKeyConvertErr == nil && len(compositePKeys) > 0 {
HandleVersionedManyToMany(context, field, compositePKeys)
} else {
+ HandleNormalManyToMany(context, field, metaValue, fieldHasVersion, compositePKeyConvertErr)
+ }
+
+ if !scope.PrimaryKeyZero() {
+ context.GetDB().Model(record).Association(meta.FieldName).Replace(field.Interface())
+ field.Set(reflect.Zero(field.Type()))
+ }
+}
+
+// HandleNormalManyToMany not only handle normal many_to_many relationship, it also handled the situation that user set the association to blank
+func HandleNormalManyToMany(context *qor.Context, field reflect.Value, metaValue *MetaValue, fieldHasVersion bool, compositePKeyConvertErr error) {
if fieldHasVersion && metaValue.Value != nil && compositePKeyConvertErr != nil {
fmt.Println("given meta value contains no version name, this might cause the association is incorrect")
}
@@ -453,7 +464,8 @@ func HandleManyToMany(context *qor.Context, scope *gorm.Scope, meta *Meta, recor
primaryKeys = []string{}
}
- // set current field value to blank
+ // set current field value to blank. This line responsible for set field to blank value when metaValue is nil
+ // which means user removed all associations
field.Set(reflect.Zero(field.Type()))
if len(primaryKeys) > 0 {
@@ -462,12 +474,6 @@ func HandleManyToMany(context *qor.Context, scope *gorm.Scope, meta *Meta, recor
}
}
- if !scope.PrimaryKeyZero() {
- context.GetDB().Model(record).Association(meta.FieldName).Replace(field.Interface())
- field.Set(reflect.Zero(field.Type()))
- }
-}
-
// HandleVersionedManyToMany handle id+version_name composite primary key, query and set the correct result to the "Many" field
// e.g. Collection.Products
// This doesn't handle compositePKeys is blank logic, if it is, this function should not be invoked
