mirror of https://github.com/go-gorm/gorm.git
Implement method interface to table name
This commit is contained in:
parent
9ef4a2669c
commit
e935b4772b
2
orm.go
2
orm.go
|
@ -26,7 +26,7 @@ type Orm struct {
|
|||
}
|
||||
|
||||
func (s *Orm) setModel(model interface{}) (err error) {
|
||||
s.TableName = "users"
|
||||
s.TableName = interfaceToTableName(model)
|
||||
s.PrimaryKey = "id"
|
||||
return
|
||||
}
|
||||
|
|
35
utils.go
35
utils.go
|
@ -4,6 +4,7 @@ import (
|
|||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
|
@ -35,6 +36,7 @@ func quoteMap(values []string) (results []string) {
|
|||
}
|
||||
return
|
||||
}
|
||||
|
||||
func toSnake(s string) string {
|
||||
buf := bytes.NewBufferString("")
|
||||
for i, v := range s {
|
||||
|
@ -46,22 +48,6 @@ func toSnake(s string) string {
|
|||
return strings.ToLower(buf.String())
|
||||
}
|
||||
|
||||
func interfaceToSnake(f interface{}) string {
|
||||
t := reflect.TypeOf(f)
|
||||
for {
|
||||
c := false
|
||||
switch t.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
|
||||
t = t.Elem()
|
||||
c = true
|
||||
}
|
||||
if !c {
|
||||
break
|
||||
}
|
||||
}
|
||||
return toSnake(t.Name())
|
||||
}
|
||||
|
||||
func snakeToUpperCamel(s string) string {
|
||||
buf := bytes.NewBufferString("")
|
||||
for _, v := range strings.Split(s, "_") {
|
||||
|
@ -73,6 +59,23 @@ func snakeToUpperCamel(s string) string {
|
|||
return buf.String()
|
||||
}
|
||||
|
||||
func interfaceToTableName(f interface{}) string {
|
||||
t := reflect.TypeOf(f)
|
||||
for {
|
||||
c := false
|
||||
switch t.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
|
||||
t = t.Elem()
|
||||
c = true
|
||||
}
|
||||
if !c {
|
||||
break
|
||||
}
|
||||
}
|
||||
reg, _ := regexp.Compile("s*$")
|
||||
return reg.ReplaceAllString(toSnake(t.Name()), "s")
|
||||
}
|
||||
|
||||
func debug(value interface{}) {
|
||||
fmt.Printf("***************\n")
|
||||
fmt.Printf("%+v\n\n", value)
|
||||
|
|
Loading…
Reference in New Issue