diff --git a/association.go b/association.go index 10be46c6..c97bc157 100644 --- a/association.go +++ b/association.go @@ -208,7 +208,14 @@ func (association *Association) Delete(values ...interface{}) *Association { ) // set foreign key to be null - association.setErr(newDB.Model(scope.Value).UpdateColumn(foreignKeyMap).Error) + modelValue := reflect.New(scope.GetModelStruct().ModelType).Interface() + if results := newDB.Model(modelValue).UpdateColumn(foreignKeyMap); results.Error == nil { + if results.RowsAffected > 0 { + scope.updatedAttrsWithValues(foreignKeyMap, false) + } + } else { + association.setErr(results.Error) + } } else if relationship.Kind == "has_one" || relationship.Kind == "has_many" { // find all relations primaryKeys := association.getPrimaryKeys(relationship.AssociationForeignFieldNames, scope.Value) diff --git a/association_test.go b/association_test.go index ddc9bc7a..92249065 100644 --- a/association_test.go +++ b/association_test.go @@ -46,6 +46,14 @@ func TestBelongsTo(t *testing.T) { t.Errorf("Query belongs to relations with Related") } + if DB.Model(&post).Association("Category").Count() == 1 { + t.Errorf("Post's category count should be 1") + } + + if DB.Model(&post).Association("MainCategory").Count() == 1 { + t.Errorf("Post's main category count should be 1") + } + // Append var category2 = Category{ Name: "Category 2", @@ -63,6 +71,10 @@ func TestBelongsTo(t *testing.T) { t.Errorf("Category should be updated with Append") } + if DB.Model(&post).Association("Category").Count() == 1 { + t.Errorf("Post's category count should be 1") + } + // Replace var category3 = Category{ Name: "Category 3", @@ -79,9 +91,14 @@ func TestBelongsTo(t *testing.T) { t.Errorf("Category should be updated with Replace") } + if DB.Model(&post).Association("Category").Count() == 1 { + t.Errorf("Post's category count should be 1") + } + // Delete DB.Model(&post).Association("Category").Delete(&category2) - DB.First(&post, post.Id) + fmt.Println(post) + fmt.Println(post.Category) if DB.Model(&post).Related(&Category{}).RecordNotFound() { t.Errorf("Should not delete any category when Delete a unrelated Category") } @@ -94,6 +111,10 @@ func TestBelongsTo(t *testing.T) { t.Errorf("Category should be deleted with Delete") } + if DB.Model(&post).Association("Category").Count() == 0 { + t.Errorf("Post's category count should be 0 after Delete") + } + // Clear DB.Model(&post).Association("Category").Append(&Category{ Name: "Category 2", @@ -108,6 +129,10 @@ func TestBelongsTo(t *testing.T) { if !DB.Model(&post).Related(&Category{}).RecordNotFound() { t.Errorf("Should not find any category after Clear") } + + if DB.Model(&post).Association("Category").Count() == 0 { + t.Errorf("Post's category count should be 0 after Clear") + } } func TestHasOne(t *testing.T) {