byat.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package model
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "gorm.io/gorm"
  6. "time"
  7. )
  8. type ControlBy struct {
  9. CreateBy int `json:"createBy" gorm:"index;comment:创建者"` // 创建者
  10. UpdateBy int `json:"updateBy" gorm:"index;comment:更新者"` // 更新者
  11. }
  12. // SetCreateBy 设置创建人id
  13. func (e *ControlBy) SetCreateBy(createBy int) {
  14. e.CreateBy = createBy
  15. }
  16. // SetUpdateBy 设置修改人id
  17. func (e *ControlBy) SetUpdateBy(updateBy int) {
  18. e.UpdateBy = updateBy
  19. }
  20. type DeptBy struct {
  21. DeptId int `json:"deptId" gorm:"index;comment:部门id"` // 部门id
  22. }
  23. // SetCreateBy 设置创建人id
  24. func (e *DeptBy) SetDeptId(deptId int) {
  25. e.DeptId = deptId
  26. }
  27. type Model struct {
  28. Id int `json:"id" gorm:"primaryKey;autoIncrement;comment:主键编码"` // 主键编码
  29. }
  30. type ModelTime struct {
  31. CreatedAt Time `json:"createdAt" gorm:"type:timestamp;comment:创建时间"` // 创建时间
  32. UpdatedAt Time `json:"updatedAt" gorm:"type:timestamp;comment:最后更新时间;autoUpdateTime"` // 最后更新时间
  33. DeletedAt gorm.DeletedAt `json:"-" gorm:"index;comment:删除时间"`
  34. }
  35. const timeFormat = "2006-01-02 15:04:05"
  36. const timezone = "Asia/Shanghai"
  37. // 全局定义
  38. type Time time.Time
  39. func (t Time) MarshalJSON() ([]byte, error) {
  40. b := make([]byte, 0, len(timeFormat)+2)
  41. if time.Time(t).IsZero() {
  42. b = append(b, '"')
  43. b = append(b, '"')
  44. return b, nil
  45. }
  46. b = append(b, '"')
  47. b = time.Time(t).AppendFormat(b, timeFormat)
  48. b = append(b, '"')
  49. return b, nil
  50. }
  51. func (t *Time) UnmarshalJSON(data []byte) (err error) {
  52. now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local)
  53. *t = Time(now)
  54. return
  55. }
  56. func (t Time) String() string {
  57. if time.Time(t).IsZero() {
  58. return ""
  59. }
  60. return time.Time(t).Format(timeFormat)
  61. }
  62. func (t Time) local() time.Time {
  63. loc, _ := time.LoadLocation(timezone)
  64. return time.Time(t).In(loc)
  65. }
  66. func (t Time) Value() (driver.Value, error) {
  67. var zeroTime time.Time
  68. var ti = time.Time(t)
  69. if ti.UnixNano() == zeroTime.UnixNano() {
  70. return nil, nil
  71. }
  72. return ti, nil
  73. }
  74. func (t *Time) Scan(v interface{}) error {
  75. value, ok := v.(time.Time)
  76. if ok {
  77. *t = Time(value)
  78. return nil
  79. }
  80. return fmt.Errorf("can not convert %v to timestamp", v)
  81. }