diff --git a/changeset.go b/changeset.go index 5505cf26..44a20e30 100644 --- a/changeset.go +++ b/changeset.go @@ -118,6 +118,7 @@ func (c Changeset) applyAssocMany(field string, mut *Mutation) { assoc = c.doc.Association(field) col, _ = assoc.Collection() muts = make([]Mutation, 0, col.Len()) + mutsCount = 0 updatedIDs = make(map[interface{}]struct{}) deletedIDs []interface{} ) @@ -130,12 +131,15 @@ func (c Changeset) applyAssocMany(field string, mut *Mutation) { if ch, ok := chs[pValue]; ok { updatedIDs[pValue] = struct{}{} + mut := Apply(doc, ch) + muts = append(muts, mut) - if amod := Apply(doc, ch); !amod.IsEmpty() { - muts = append(muts, amod) + if !mut.IsEmpty() { + mutsCount++ } } else { muts = append(muts, Apply(doc, newStructset(doc, false))) + mutsCount++ } } @@ -148,7 +152,7 @@ func (c Changeset) applyAssocMany(field string, mut *Mutation) { } } - if len(muts) > 0 || len(deletedIDs) > 0 { + if mutsCount > 0 || len(deletedIDs) > 0 { mut.SetAssoc(field, muts...) mut.SetDeletedIDs(field, deletedIDs) } diff --git a/changeset_test.go b/changeset_test.go index 34dda865..fbf814c1 100644 --- a/changeset_test.go +++ b/changeset_test.go @@ -503,6 +503,7 @@ func TestChangeset_hasMany(t *testing.T) { Transactions: []Transaction{ {ID: 11, Item: "Book", Status: "pending"}, {ID: 12, Item: "Eraser", Status: "pending"}, + {ID: 13, Item: "Pencil", Status: "pending"}, }, } snapshots = [][]interface{}{ @@ -576,6 +577,10 @@ func TestChangeset_hasMany(t *testing.T) { "address_id": Set("address_id", 0), }, }, + { + Cascade: true, + Mutates: nil, // nil mutates to satisfy repository saveHasMany check + }, }, DeletedIDs: []interface{}{12}, }, diff --git a/repository.go b/repository.go index cd9f9d5c..c32a8a42 100644 --- a/repository.go +++ b/repository.go @@ -375,7 +375,7 @@ func (r repository) insert(cw contextWrapper, doc *Document, mutation Mutation) } // update primary value - if pField != "" { + if pField != "" && !isZero(pValue) { doc.SetValue(pField, pValue) } @@ -740,8 +740,10 @@ func (r repository) saveHasMany(cw contextWrapper, doc *Document, mutation *Muta muts[i], muts[updateCount] = muts[updateCount], muts[i] } - if err := r.update(cw, assocDoc, muts[updateCount], filter); err != nil { - return err + if !muts[updateCount].IsEmpty() { + if err := r.update(cw, assocDoc, muts[updateCount], filter); err != nil { + return err + } } updateCount++