Fix delete many2many associations

This commit is contained in:
Jinzhu 2015-01-16 10:15:53 +08:00
parent ebe5f191a9
commit b7554a2cb0
2 changed files with 15 additions and 2 deletions

View File

@ -97,8 +97,12 @@ func (association *Association) Delete(values ...interface{}) *Association {
relationship := association.Field.Relationship
// many to many
if relationship.Kind == "many_to_many" {
whereSql := fmt.Sprintf("%v.%v IN (?)", relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.AssociationForeignKey)))
association.Scope.db.Model("").Table(relationship.JoinTable).Where(whereSql, primaryKeys).Delete("")
whereSql := fmt.Sprintf("%v.%v = ? AND %v.%v IN (?)",
relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.ForeignKey)),
relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.AssociationForeignKey)))
association.Scope.db.Model("").Table(relationship.JoinTable).
Where(whereSql, association.PrimaryKey, primaryKeys).Delete("")
} else {
association.err(errors.New("delete only support many to many"))
}

View File

@ -1,6 +1,7 @@
package gorm_test
import "testing"
import "github.com/jinzhu/gorm"
type Cat struct {
@ -207,11 +208,19 @@ func TestManyToMany(t *testing.T) {
languages = []Language{}
DB.Where("name IN (?)", []string{"CC", "DD"}).Find(&languages)
user2 := User{Name: "Many2Many_User2", Languages: languages}
DB.Save(&user2)
DB.Model(&user).Association("Languages").Delete(languages, &languages)
if DB.Model(&user).Association("Languages").Count() != len(totalLanguages)-3 {
t.Errorf("Relations should be deleted with Delete")
}
if DB.Model(&user2).Association("Languages").Count() == 0 {
t.Errorf("Other user's relations should not be deleted")
}
// Replace
var languageB Language
DB.Where("name = ?", "BB").First(&languageB)