mirror of https://github.com/go-gorm/gorm.git
Make clear works
This commit is contained in:
parent
5a95050464
commit
ba74a9545b
|
@ -138,7 +138,15 @@ func (association *Association) Replace(values ...interface{}) *Association {
|
||||||
return 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
|
return association
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -190,17 +190,19 @@ func TestManyToMany(t *testing.T) {
|
||||||
// Replace
|
// Replace
|
||||||
var languageB Language
|
var languageB Language
|
||||||
db.Where("name = ?", "BB").First(&languageB)
|
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 {
|
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"}})
|
db.Model(&user).Association("Languages").Replace(&[]Language{{Name: "FF"}, {Name: "JJ"}})
|
||||||
if db.Model(&user).Association("Languages").Count() != len([]string{"FF", "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{})
|
// Clear
|
||||||
// db.Model(&User{}).Related(&[]Language{}, "Languages")
|
db.Model(&user).Association("Languages").Clear()
|
||||||
// SELECT `languages`.* FROM `languages` INNER JOIN `user_languages` ON `languages`.`id` = `user_languages`.`language_id` WHERE `user_languages`.`user_id` = 111
|
if db.Model(&user).Association("Languages").Count() != 0 {
|
||||||
|
t.Errorf("Relations should be cleared")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue