Fix join table foreign key in snake_case

This commit is contained in:
Jinzhu 2020-07-04 07:24:30 +08:00
parent 2416eabd3f
commit d4f8a52442
2 changed files with 12 additions and 4 deletions

View File

@ -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 {

View File

@ -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},
},
})
}