mirror of https://github.com/go-gorm/gorm.git
Add model.go file
This commit is contained in:
parent
95b7263ec7
commit
5cfad9d35b
|
@ -0,0 +1,48 @@
|
|||
package gorm
|
||||
|
||||
import "reflect"
|
||||
|
||||
type Model struct {
|
||||
Data interface{}
|
||||
}
|
||||
|
||||
func toModel(value interface{}) *Model {
|
||||
var model Model
|
||||
model.Data = value
|
||||
return &model
|
||||
}
|
||||
|
||||
func (m *Model) ColumnsAndValues() (columns []string, values []interface{}) {
|
||||
typ := reflect.TypeOf(m.Data).Elem()
|
||||
|
||||
for i := 0; i < typ.NumField(); i++ {
|
||||
p := typ.Field(i)
|
||||
if !p.Anonymous {
|
||||
columns = append(columns, toSnake(p.Name))
|
||||
value := reflect.ValueOf(m.Data).Elem().FieldByName(p.Name)
|
||||
values = append(values, value.Interface())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Model) Columns() (columns []string) {
|
||||
typ := reflect.TypeOf(m.Data).Elem()
|
||||
|
||||
for i := 0; i < typ.NumField(); i++ {
|
||||
p := typ.Field(i)
|
||||
if !p.Anonymous {
|
||||
columns = append(columns, toSnake(p.Name))
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (model *Model) MissingColumns() (results []string) {
|
||||
return
|
||||
}
|
||||
|
||||
func (model *Model) ColumnType(column string) (result string) {
|
||||
return
|
||||
}
|
2
orm.go
2
orm.go
|
@ -13,6 +13,7 @@ type Orm struct {
|
|||
Error error
|
||||
Sql string
|
||||
SqlVars []interface{}
|
||||
Model *Model
|
||||
|
||||
db *sql.DB
|
||||
whereClause []map[string]interface{}
|
||||
|
@ -24,6 +25,7 @@ type Orm struct {
|
|||
}
|
||||
|
||||
func (s *Orm) setModel(model interface{}) (err error) {
|
||||
s.Model = toModel(model)
|
||||
s.TableName = interfaceToTableName(model)
|
||||
s.PrimaryKey = "id"
|
||||
return
|
||||
|
|
2
sql.go
2
sql.go
|
@ -71,7 +71,7 @@ func (s *Orm) query(out interface{}) {
|
|||
}
|
||||
|
||||
func (s *Orm) saveSql(value interface{}) {
|
||||
columns, values := modelValues(value)
|
||||
columns, values := s.Model.ColumnsAndValues()
|
||||
s.Sql = fmt.Sprintf(
|
||||
"INSERT INTO \"%v\" (%v) VALUES (%v)",
|
||||
s.TableName,
|
||||
|
|
14
utils.go
14
utils.go
|
@ -8,20 +8,6 @@ import (
|
|||
"strings"
|
||||
)
|
||||
|
||||
func modelValues(m interface{}) (columns []string, values []interface{}) {
|
||||
typ := reflect.TypeOf(m).Elem()
|
||||
|
||||
for i := 0; i < typ.NumField(); i++ {
|
||||
p := typ.Field(i)
|
||||
if !p.Anonymous {
|
||||
columns = append(columns, toSnake(p.Name))
|
||||
value := reflect.ValueOf(m).Elem().FieldByName(p.Name)
|
||||
values = append(values, value.Interface())
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func valuesToBinVar(values []interface{}) string {
|
||||
var sqls []string
|
||||
for index, _ := range values {
|
||||
|
|
Loading…
Reference in New Issue