Refactor Fields

This commit is contained in:
Jinzhu 2015-02-16 17:47:07 +08:00
parent 2d866090e4
commit de3f2a5c46
3 changed files with 18 additions and 50 deletions

View File

@ -38,19 +38,20 @@ func (field *Field) Set(value interface{}) (err error) {
return
}
type relationship struct {
JoinTable string
ForeignKey string
ForeignType string
AssociationForeignKey string
Kind string
// Fields get value's fields
func (scope *Scope) Fields() map[string]*Field {
fields := map[string]*Field{}
structFields := scope.GetStructFields()
for _, structField := range structFields {
fields[structField.DBName] = scope.getField(structField)
}
return fields
}
// FIXME
func (r relationship) ForeignDBName() string {
return ToSnake(r.ForeignKey)
}
func (r relationship) AssociationForeignDBName(name string) string {
return ToSnake(r.AssociationForeignKey)
func (scope *Scope) getField(structField *StructField) *Field {
field := Field{StructField: structField}
field.Field = scope.IndirectValue().FieldByName(structField.Name)
return &field
}

View File

@ -43,7 +43,7 @@ type Relationship struct {
JoinTable string
}
func (scope *Scope) GenerateSqlTag(field *StructField) {
func (scope *Scope) generateSqlTag(field *StructField) {
var sqlType string
reflectValue := reflect.Indirect(reflect.New(field.Struct.Type))
@ -246,7 +246,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
modelStruct.PrimaryKeyField = field
}
scope.GenerateSqlTag(field)
scope.generateSqlTag(field)
}
}

View File

@ -95,28 +95,7 @@ func (scope *Scope) HasError() bool {
}
func (scope *Scope) PrimaryKeyField() *Field {
if scope.primaryKeyField == nil {
var indirectValue = scope.IndirectValue()
clone := scope
// FIXME
if indirectValue.Kind() == reflect.Slice {
typ := indirectValue.Type().Elem()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
clone = scope.New(reflect.New(typ).Elem().Addr().Interface())
}
for _, field := range clone.Fields() {
if field.IsPrimaryKey {
scope.primaryKeyField = field
break
}
}
}
return scope.primaryKeyField
return scope.getField(scope.GetModelStruct().PrimaryKeyField)
}
// PrimaryKey get the primary key's column name
@ -135,7 +114,7 @@ func (scope *Scope) PrimaryKeyZero() bool {
// PrimaryKeyValue get the primary key's value
func (scope *Scope) PrimaryKeyValue() interface{} {
if field := scope.PrimaryKeyField(); field != nil {
if field := scope.PrimaryKeyField(); field != nil && field.Field.IsValid() {
return field.Field.Interface()
} else {
return 0
@ -294,18 +273,6 @@ func (scope *Scope) FieldByName(name string) (field *Field, ok bool) {
return nil, false
}
// Fields get value's fields
func (scope *Scope) Fields() map[string]*Field {
fields := map[string]*Field{}
structFields := scope.GetStructFields()
for _, structField := range structFields {
field := Field{StructField: structField}
fields[field.DBName] = &field
}
return fields
}
// Raw set sql
func (scope *Scope) Raw(sql string) *Scope {
scope.Sql = strings.Replace(sql, "$$", "?", -1)