dws18.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package model
  4. import (
  5. "time"
  6. "gorm.io/gorm"
  7. )
  8. type Dws18 struct {
  9. ID int64 `gorm:"primary_key" json:"-"`
  10. ModelNo string `json:"model_no"`
  11. EngineType string `json:"engine_type"`
  12. CreatedAt int64 `json:"-"`
  13. UpdatedAt int64 `json:"-"`
  14. }
  15. func (Dws18) TableName() string {
  16. return "t_adm_dws18"
  17. }
  18. // Insert 插入一条记录
  19. func (p *Dws18) Insert(db *gorm.DB) error {
  20. timeNow := time.Now().Unix()
  21. p.CreatedAt = timeNow
  22. p.UpdatedAt = timeNow
  23. err := db.Create(p).Error
  24. return err
  25. }
  26. func (p *Dws18) InsertByMap(db *gorm.DB, data map[string]interface{}) error {
  27. data["updated_at"] = time.Now().Unix()
  28. err := db.Model(p).Create(data).Error
  29. return err
  30. }
  31. func (p *Dws18) Delete(db *gorm.DB, filter map[string]interface{}) error {
  32. err := db.Where(filter).Delete(p).Error
  33. return err
  34. }
  35. func (p *Dws18) Save(db *gorm.DB) error {
  36. timeNow := time.Now().Unix()
  37. p.UpdatedAt = timeNow
  38. //db.Model().Update()
  39. err := db.Save(p).Error
  40. return err
  41. }
  42. func (p *Dws18) Update(db *gorm.DB) error {
  43. timeNow := time.Now().Unix()
  44. p.CreatedAt = 0
  45. p.UpdatedAt = timeNow
  46. err := db.Model(p).Updates(p).Error
  47. return err
  48. }
  49. func (p *Dws18) UpdateByMap(db *gorm.DB, data map[string]interface{}) error {
  50. data["updated_at"] = time.Now().Unix()
  51. err := db.Model(p).Updates(data).Error
  52. return err
  53. }
  54. // 通过结构体变量更新字段值, gorm库会忽略零值字段。就是字段值等于0, nil, "", false这些值会被忽略掉,不会更新。如果想更新零值,可以使用map类型替代结构体。
  55. func (p *Dws18) UpdateSome(db *gorm.DB, filed map[string]interface{}) error {
  56. /*if filed == nil {
  57. return errors.ParamsError
  58. }*/
  59. timeNow := time.Now().Unix()
  60. filed["updated_at"] = timeNow
  61. err := db.Model(p).Updates(filed).Error
  62. return err
  63. }
  64. func (p *Dws18) Query(db *gorm.DB, filter map[string]interface{}) error {
  65. err := db.Where(filter).Order("id DESC").Find(p).Error
  66. if p.ID == 0 {
  67. return gorm.ErrRecordNotFound
  68. }
  69. return err
  70. }
  71. func (p *Dws18) QueryAll(db *gorm.DB, filter map[string]interface{}, out interface{}) error {
  72. err := db.Where(filter).Find(out).Error
  73. return err
  74. }