feat: adjust SetupJoinTable func if..else code (#4680)

This commit is contained in:
heige 2021-10-08 11:05:50 +08:00 committed by GitHub
parent 5d91ddac8c
commit c13f3011f9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 31 additions and 29 deletions

32
gorm.go
View File

@ -387,30 +387,36 @@ func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interfac
modelSchema, joinSchema *schema.Schema
)
if err := stmt.Parse(model); err == nil {
err := stmt.Parse(model)
if err != nil {
return err
}
modelSchema = stmt.Schema
} else {
err = stmt.Parse(joinTable)
if err != nil {
return err
}
if err := stmt.Parse(joinTable); err == nil {
joinSchema = stmt.Schema
} else {
return err
relation, ok := modelSchema.Relationships.Relations[field]
isRelation := ok && relation.JoinTable != nil
if !isRelation {
return fmt.Errorf("failed to found relation: %s", field)
}
if relation, ok := modelSchema.Relationships.Relations[field]; ok && relation.JoinTable != nil {
for _, ref := range relation.References {
if f := joinSchema.LookUpField(ref.ForeignKey.DBName); f != nil {
f := joinSchema.LookUpField(ref.ForeignKey.DBName)
if f == nil {
return fmt.Errorf("missing field %s for join table", ref.ForeignKey.DBName)
}
f.DataType = ref.ForeignKey.DataType
f.GORMDataType = ref.ForeignKey.GORMDataType
if f.Size == 0 {
f.Size = ref.ForeignKey.Size
}
ref.ForeignKey = f
} else {
return fmt.Errorf("missing field %s for join table", ref.ForeignKey.DBName)
}
}
for name, rel := range relation.JoinTable.Relationships.Relations {
@ -419,11 +425,7 @@ func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interfac
joinSchema.Relationships.Relations[name] = rel
}
}
relation.JoinTable = joinSchema
} else {
return fmt.Errorf("failed to found relation: %s", field)
}
return nil
}