forked from zhufuyi/sponge
/
base_model.go
47 lines (38 loc) · 1.24 KB
/
base_model.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package mysql
import (
"reflect"
"time"
"github.com/huandu/xstrings"
"gorm.io/gorm"
)
//type Model = gorm.Model
// Model embedded structs, add `gorm: "embedded"` when defining table structs
type Model struct {
ID uint64 `gorm:"column:id;AUTO_INCREMENT;primary_key" json:"id"`
CreatedAt time.Time `gorm:"column:created_at" json:"createdAt"`
UpdatedAt time.Time `gorm:"column:updated_at" json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index" json:"-"`
}
// Model2 embedded structs, json tag named is snake case
type Model2 struct {
ID uint64 `gorm:"column:id;AUTO_INCREMENT;primary_key" json:"id"`
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;index" json:"-"`
}
// KV map type
type KV = map[string]interface{}
// GetTableName get table name
func GetTableName(object interface{}) string {
tableName := ""
typeof := reflect.TypeOf(object)
switch typeof.Kind() {
case reflect.Ptr:
tableName = typeof.Elem().Name()
case reflect.Struct:
tableName = typeof.Name()
default:
return tableName
}
return xstrings.ToSnakeCase(tableName)
}