Add Replace support for has many associations

This commit is contained in:
Jinzhu 2015-12-25 19:08:10 +08:00
parent a00fb4db04
commit 4719ee7b1f
2 changed files with 10 additions and 2 deletions

View File

@ -126,7 +126,8 @@ func (association *Association) Replace(values ...interface{}) *Association {
if relationship.Kind == "many_to_many" { if relationship.Kind == "many_to_many" {
association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, query, relationship)) association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, query, relationship))
} else if relationship.Kind == "has_one" || relationship.Kind == "has_many" { } else if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
query.Update(foreignKeyMap) fieldValue := reflect.New(association.Field.Field.Type()).Interface()
association.setErr(query.Model(fieldValue).UpdateColumn(foreignKeyMap).Error)
} }
return association return association
} }

View File

@ -175,11 +175,18 @@ func TestHasMany(t *testing.T) {
var comments3 []Comment var comments3 []Comment
DB.Model(&post).Related(&comments3) DB.Model(&post).Related(&comments3)
if !compareComments(comments3, []string{"Comment 3"}) { if !compareComments(comments3, []string{"Comment 3"}) {
fmt.Println(comments3)
t.Errorf("Delete an existing resource for has many relations") t.Errorf("Delete an existing resource for has many relations")
} }
// Replace // Replace
DB.Model(&post).Association("Comments").Replace(&Comment{Content: "Comment 4"}, &Comment{Content: "Comment 5"})
var comments4 []Comment
DB.Model(&post).Related(&comments4)
if !compareComments(comments4, []string{"Comment 4", "Comment 5"}) {
t.Errorf("Replace has many relations")
}
// Clear // Clear
} }