Refactor model struct

This commit is contained in:
Jinzhu 2015-02-18 11:37:08 +08:00
parent 5c478b46e1
commit 9e5c64d611
1 changed files with 96 additions and 91 deletions

View File

@ -156,7 +156,8 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
}
}
// Set fields
// Get all fields
fields := []*StructField{}
for i := 0; i < scopeType.NumField(); i++ {
if fieldStruct := scopeType.Field(i); ast.IsExported(fieldStruct.Name) {
field := &StructField{
@ -185,7 +186,14 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
} else {
field.DBName = ToDBName(fieldStruct.Name)
}
}
fields = append(fields, field)
}
}
for _, field := range fields {
if !field.IsIgnored {
fieldStruct := field.Struct
fieldType, indirectType := fieldStruct.Type, fieldStruct.Type
if indirectType.Kind() == reflect.Ptr {
indirectType = indirectType.Elem()
@ -199,6 +207,8 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
field.IsNormal = true
}
if !field.IsNormal {
gormSettings := parseTagSetting(field.Tag.Get("gorm"))
many2many := gormSettings["MANY2MANY"]
foreignKey := gormSettings["FOREIGNKEY"]
foreignType := gormSettings["FOREIGNTYPE"]
@ -208,7 +218,6 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
foreignType = polymorphic + "Type"
}
if !field.IsNormal {
switch indirectType.Kind() {
case reflect.Slice:
typ := indirectType.Elem()
@ -247,10 +256,10 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
}
case reflect.Struct:
if _, ok := gormSettings["EMBEDDED"]; ok || fieldStruct.Anonymous {
for _, field := range scope.New(reflect.New(indirectType).Interface()).GetStructFields() {
field = field.clone()
field.Names = append([]string{fieldStruct.Name}, field.Names...)
modelStruct.StructFields = append(modelStruct.StructFields, field)
for _, f := range scope.New(reflect.New(indirectType).Interface()).GetStructFields() {
f = f.clone()
f.Names = append([]string{fieldStruct.Name}, f.Names...)
modelStruct.StructFields = append(modelStruct.StructFields, f)
}
break
} else {
@ -279,17 +288,11 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
Kind: kind,
}
}
default:
field.IsNormal = true
}
}
}
modelStruct.StructFields = append(modelStruct.StructFields, field)
}
}
for _, field := range modelStruct.StructFields {
if field.IsNormal {
if modelStruct.PrimaryKeyField == nil && field.DBName == "id" {
field.IsPrimaryKey = true
@ -301,6 +304,8 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
}
}
}
modelStruct.StructFields = append(modelStruct.StructFields, field)
}
if scope.db != nil {
scope.db.parent.ModelStructs[scopeType] = &modelStruct