From f2adb088c598400086b6e67506ffee38780e9c3f Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 3 Sep 2020 16:11:15 +0800 Subject: [PATCH] Set field size from primary fields to foreign fields --- gorm.go | 3 +++ schema/relationship.go | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/gorm.go b/gorm.go index ed01ccfe..8efd8a73 100644 --- a/gorm.go +++ b/gorm.go @@ -319,6 +319,9 @@ func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interfac if f := joinSchema.LookUpField(ref.ForeignKey.DBName); f != nil { 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 %v for join table", ref.ForeignKey.DBName) diff --git a/schema/relationship.go b/schema/relationship.go index aa992b84..47b948dc 100644 --- a/schema/relationship.go +++ b/schema/relationship.go @@ -165,6 +165,9 @@ func (schema *Schema) buildPolymorphicRelation(relation *Relationship, field *Fi // use same data type for foreign keys relation.Polymorphic.PolymorphicID.DataType = primaryKeyField.DataType relation.Polymorphic.PolymorphicID.GORMDataType = primaryKeyField.GORMDataType + if relation.Polymorphic.PolymorphicID.Size == 0 { + relation.Polymorphic.PolymorphicID.Size = primaryKeyField.Size + } relation.References = append(relation.References, &Reference{ PrimaryKey: primaryKeyField, @@ -301,6 +304,9 @@ func (schema *Schema) buildMany2ManyRelation(relation *Relationship, field *Fiel // use same data type for foreign keys f.DataType = fieldsMap[f.Name].DataType f.GORMDataType = fieldsMap[f.Name].GORMDataType + if f.Size == 0 { + f.Size = fieldsMap[f.Name].Size + } relation.JoinTable.PrimaryFields = append(relation.JoinTable.PrimaryFields, f) ownPriamryField := schema == fieldsMap[f.Name].Schema && ownFieldsMap[f.Name] @@ -436,6 +442,9 @@ func (schema *Schema) guessRelation(relation *Relationship, field *Field, gl gue // use same data type for foreign keys foreignField.DataType = primaryFields[idx].DataType foreignField.GORMDataType = primaryFields[idx].GORMDataType + if foreignField.Size == 0 { + foreignField.Size = primaryFields[idx].Size + } relation.References = append(relation.References, &Reference{ PrimaryKey: primaryFields[idx],