From d4f8a524423baf81aecfc6caf2780eb14e2eb187 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 4 Jul 2020 07:24:30 +0800 Subject: [PATCH] Fix join table foreign key in snake_case --- schema/relationship.go | 4 ++-- schema/relationship_test.go | 12 ++++++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/schema/relationship.go b/schema/relationship.go index a13d53b9..0967f8c8 100644 --- a/schema/relationship.go +++ b/schema/relationship.go @@ -210,7 +210,7 @@ func (schema *Schema) buildMany2ManyRelation(relation *Relationship, field *Fiel for idx, ownField := range ownForeignFields { joinFieldName := schema.Name + ownField.Name if len(joinForeignKeys) > idx { - joinFieldName = joinForeignKeys[idx] + joinFieldName = strings.Title(joinForeignKeys[idx]) } ownFieldsMap[joinFieldName] = true @@ -226,7 +226,7 @@ func (schema *Schema) buildMany2ManyRelation(relation *Relationship, field *Fiel for idx, relField := range refForeignFields { joinFieldName := relation.FieldSchema.Name + relField.Name if len(joinReferences) > idx { - joinFieldName = joinReferences[idx] + joinFieldName = strings.Title(joinReferences[idx]) } if _, ok := ownFieldsMap[joinFieldName]; ok { diff --git a/schema/relationship_test.go b/schema/relationship_test.go index defba9ce..2c09f528 100644 --- a/schema/relationship_test.go +++ b/schema/relationship_test.go @@ -138,8 +138,9 @@ func TestMany2ManyOverrideForeignKeyAndReferences(t *testing.T) { type User struct { gorm.Model - Profiles []Profile `gorm:"many2many:user_profiles;ForeignKey:Refer;JoinForeignKey:UserReferID;References:UserRefer;JoinReferences:ProfileRefer"` - Refer uint + Profiles []Profile `gorm:"many2many:user_profiles;ForeignKey:Refer;JoinForeignKey:UserReferID;References:UserRefer;JoinReferences:ProfileRefer"` + Profiles2 []Profile `gorm:"many2many:user_profiles2;ForeignKey:refer;JoinForeignKey:user_refer_id;References:user_refer;JoinReferences:profile_refer"` + Refer uint } checkStructRelation(t, &User{}, Relation{ @@ -149,6 +150,13 @@ func TestMany2ManyOverrideForeignKeyAndReferences(t *testing.T) { {"Refer", "User", "UserReferID", "user_profiles", "", true}, {"UserRefer", "Profile", "ProfileRefer", "user_profiles", "", false}, }, + }, Relation{ + Name: "Profiles2", Type: schema.Many2Many, Schema: "User", FieldSchema: "Profile", + JoinTable: JoinTable{Name: "user_profiles2", Table: "user_profiles2"}, + References: []Reference{ + {"Refer", "User", "User_refer_id", "user_profiles2", "", true}, + {"UserRefer", "Profile", "Profile_refer", "user_profiles2", "", false}, + }, }) }