mirror of https://github.com/go-gorm/gorm.git
feat: adjust SetupJoinTable func if..else code (#4680)
This commit is contained in:
parent
5d91ddac8c
commit
c13f3011f9
32
gorm.go
32
gorm.go
|
@ -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
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue