Merge pull request #2331 from xwjdsh/bugfix/fix-many2many-table-name

fix the table name of many2many
This commit is contained in:
Emir Beganović 2019-04-11 08:14:42 +02:00 committed by GitHub
commit fdd41cf0b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 1 deletions

View File

@ -289,6 +289,9 @@ type SelfReferencingUser struct {
func TestSelfReferencingMany2ManyColumn(t *testing.T) { func TestSelfReferencingMany2ManyColumn(t *testing.T) {
DB.DropTable(&SelfReferencingUser{}, "UserFriends") DB.DropTable(&SelfReferencingUser{}, "UserFriends")
DB.AutoMigrate(&SelfReferencingUser{}) DB.AutoMigrate(&SelfReferencingUser{})
if !DB.HasTable("UserFriends") {
t.Errorf("auto migrate error, table UserFriends should be created")
}
friend1 := SelfReferencingUser{Name: "friend1_m2m"} friend1 := SelfReferencingUser{Name: "friend1_m2m"}
if err := DB.Create(&friend1).Error; err != nil { if err := DB.Create(&friend1).Error; err != nil {
@ -313,6 +316,14 @@ func TestSelfReferencingMany2ManyColumn(t *testing.T) {
t.Errorf("Should find created friends correctly") t.Errorf("Should find created friends correctly")
} }
var count int
if err := DB.Table("UserFriends").Count(&count).Error; err != nil {
t.Errorf("no error should happen, but got %v", err)
}
if count == 0 {
t.Errorf("table UserFriends should have records")
}
var newUser = SelfReferencingUser{} var newUser = SelfReferencingUser{}
if err := DB.Preload("Friends").First(&newUser, "id = ?", user.ID).Error; err != nil { if err := DB.Preload("Friends").First(&newUser, "id = ?", user.ID).Error; err != nil {

View File

@ -340,7 +340,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
} }
joinTableHandler := JoinTableHandler{} joinTableHandler := JoinTableHandler{}
joinTableHandler.Setup(relationship, ToTableName(many2many), reflectType, elemType) joinTableHandler.Setup(relationship, many2many, reflectType, elemType)
relationship.JoinTableHandler = &joinTableHandler relationship.JoinTableHandler = &joinTableHandler
field.Relationship = relationship field.Relationship = relationship
} else { } else {