struct fields with column tag will force other fields with no column tag be ignored to avoid duplicated column name issue
This commit is contained in:
parent
59408390c2
commit
a2404b6852
@ -633,6 +633,28 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
|
||||
}
|
||||
}
|
||||
|
||||
// look for field which has tag COLUMN assigned, if found any, set other fields which has the same DBName, while have no COLUMN tag assigned, to IsIgnored = true
|
||||
for _, v := range modelStruct.StructFields {
|
||||
if column, ok := v.TagSettingsGet("COLUMN"); ok {
|
||||
for k, field := range modelStruct.StructFields {
|
||||
if _, ok := field.TagSettingsGet("COLUMN"); ok {
|
||||
continue
|
||||
}
|
||||
if field.DBName == column {
|
||||
ignoredField := &StructField{
|
||||
Struct: field.Struct,
|
||||
Name: field.Name,
|
||||
Names: field.Names,
|
||||
Tag: field.Tag,
|
||||
TagSettings: field.TagSettings,
|
||||
IsIgnored: true,
|
||||
}
|
||||
modelStruct.StructFields[k] = ignoredField
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(modelStruct.PrimaryFields) == 0 {
|
||||
if field := getForeignField("id", modelStruct.StructFields); field != nil {
|
||||
field.IsPrimaryKey = true
|
||||
|
@ -91,3 +91,23 @@ func TestModelStructRaceDifferentModel(t *testing.T) {
|
||||
|
||||
done.Wait()
|
||||
}
|
||||
|
||||
type ModelSameColumnName struct {
|
||||
gorm.Model
|
||||
ID string `gorm:"column:id"`
|
||||
}
|
||||
|
||||
func TestModelStructIgnoreNoTagSameDBNameColumn(t *testing.T) {
|
||||
sf := DB.NewScope(&ModelSameColumnName{}).GetStructFields()
|
||||
|
||||
columnIDcount := 0
|
||||
for _, v := range sf {
|
||||
if v.DBName == "id" {
|
||||
columnIDcount++
|
||||
}
|
||||
}
|
||||
|
||||
if columnIDcount > 1 {
|
||||
t.Fatal("fields have same name while contains no column tag not being ignored")
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user