device_command.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package model
  2. import (
  3. "fmt"
  4. "sparrow/pkg/models"
  5. "github.com/jinzhu/gorm"
  6. )
  7. // DeviceCommandModel ``
  8. type DeviceCommandModel struct {
  9. db *gorm.DB
  10. }
  11. // Init 初始化
  12. func (a *DeviceCommandModel) Init(_db *gorm.DB) *DeviceCommandModel {
  13. a.db = _db
  14. return a
  15. }
  16. // Create 添加
  17. func (a *DeviceCommandModel) Create(item *models.DeviceCommand) error {
  18. cache := getCache()
  19. key := fmt.Sprintf("DeviceCommand:%s", item.RecordID)
  20. err := a.db.Save(item).Error
  21. if err == nil {
  22. cache.Set(key, item)
  23. }
  24. return err
  25. }
  26. // Delete 删除
  27. func (a *DeviceCommandModel) Delete(item *models.DeviceCommand) error {
  28. cache := getCache()
  29. key := fmt.Sprintf("DeviceCommand:%s", item.RecordID)
  30. if _, ok := cache.Get(key); ok {
  31. cache.Delete(key)
  32. }
  33. // 删除关联的 data
  34. a.db.Where("command_id = ?", item.RecordID).Delete(&models.DeviceCommandData{})
  35. return a.db.Delete(item).Error
  36. }
  37. // Update 更新
  38. func (a *DeviceCommandModel) Update(item *models.DeviceCommand) (data models.DeviceCommand, err error) {
  39. // 先删除旧的 data
  40. a.db.Where("command_id = ?", item.RecordID).Delete(&models.DeviceCommandData{})
  41. // 重新保存
  42. err = a.db.Save(item).Error
  43. if err == nil {
  44. cache := getCache()
  45. key := fmt.Sprintf("DeviceCommand:%s", item.RecordID)
  46. if _, ok := cache.Get(key); ok {
  47. cache.Delete(key)
  48. }
  49. cache.Set(key, item)
  50. }
  51. return
  52. }
  53. // GetListByDeviceTypeId 根据设备类型id获取指令列表
  54. func (a *DeviceCommandModel) GetListByDeviceTypeId(deviceTypeId string, pi, ps int, name string) (datas []models.DeviceCommand, total int, err error) {
  55. tx := a.db.Where("device_type_id = ?", deviceTypeId)
  56. if name != "" {
  57. tx = tx.Where("name like ?", "%"+name+"%")
  58. }
  59. err = tx.Preload("Data").Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
  60. tx.Model(&models.DeviceCommand{}).Where("device_type_id = ?", deviceTypeId).Count(&total)
  61. return
  62. }
  63. // QueryOne 获取单个内容
  64. func (a *DeviceCommandModel) QueryOne(recordID string) (data models.DeviceCommand, err error) {
  65. cache := getCache()
  66. key := fmt.Sprintf("DeviceCommand:%s", recordID)
  67. if v, ok := cache.Get(key); ok {
  68. _d := v.(*models.DeviceCommand)
  69. data = *_d
  70. } else {
  71. err = a.db.Preload("Data").Where("record_id = ?", recordID).First(&data).Error
  72. if err == nil {
  73. cache.Set(key, &data)
  74. }
  75. }
  76. return
  77. }