forked from mirror/gorm
Fix delete many2many associations
This commit is contained in:
parent
ebe5f191a9
commit
b7554a2cb0
|
@ -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"))
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue