Make clear works

This commit is contained in:
Jinzhu 2014-07-30 22:15:31 +08:00
parent 5a95050464
commit ba74a9545b
2 changed files with 17 additions and 7 deletions

View File

@ -138,7 +138,15 @@ func (association *Association) Replace(values ...interface{}) *Association {
return association
}
func (association *Association) Clear(value interface{}) *Association {
func (association *Association) Clear() *Association {
relationship := association.Field.Relationship
scope := association.Scope
if relationship.kind == "many_to_many" {
whereSql := fmt.Sprintf("%v.%v = ?", relationship.joinTable, scope.Quote(ToSnake(relationship.foreignKey)))
scope.db.Model("").Table(relationship.joinTable).Where(whereSql, association.PrimaryKey).Delete("")
} else {
association.err(errors.New("clear only support many to many"))
}
return association
}

View File

@ -190,17 +190,19 @@ func TestManyToMany(t *testing.T) {
// Replace
var languageB Language
db.Where("name = ?", "BB").First(&languageB)
db.Debug().Model(&user).Association("Languages").Replace(languageB)
db.Model(&user).Association("Languages").Replace(languageB)
if db.Model(&user).Association("Languages").Count() != 1 {
t.Errorf("Relations should be deleted with Delete")
t.Errorf("Relations should be replaced")
}
db.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}})
if db.Model(&user).Association("Languages").Count() != len([]string{"FF", "JJ"}) {
t.Errorf("Relations should be deleted with Delete")
t.Errorf("Relations should be replaced")
}
// db.Model(&User{}).Many2Many("Languages").Replace(&[]Language{})
// db.Model(&User{}).Related(&[]Language{}, "Languages")
// SELECT `languages`.* FROM `languages` INNER JOIN `user_languages` ON `languages`.`id` = `user_languages`.`language_id` WHERE `user_languages`.`user_id` = 111
// Clear
db.Model(&user).Association("Languages").Clear()
if db.Model(&user).Association("Languages").Count() != 0 {
t.Errorf("Relations should be cleared")
}
}