tunnel.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package dao
  2. import (
  3. "gorm.io/gorm"
  4. "server/global"
  5. )
  6. type Tunnel struct {
  7. global.GVA_MODEL
  8. TunnelSn string `json:"tunnelSn" gorm:"comment:隧道序号"`
  9. Name string `json:"name" gorm:"comment:名称"`
  10. Tactics int `json:"tactics" gorm:"comment:策略"`
  11. RegionId int `json:"regionId" gorm:"column:region_id"`
  12. Region Region `json:"region" gorm:"foreignKey:RegionId"` // 关系
  13. TimeId int `json:"timeId" gorm:"comment:定时id"`
  14. TunnelTime TunnelTime `json:"tunnelTime" gorm:"foreignKey:TimeId"`
  15. Users []SysUser `json:"users" gorm:"many2many:user_tunnel"`
  16. Devices []Device `json:"devices" gorm:"foreignKey:TunnelId"`
  17. }
  18. func (Tunnel) TableName() string {
  19. return "tunnel"
  20. }
  21. func QueryAllTunnels() (tunnels []Tunnel, err error) {
  22. err = global.GVA_DB.Find(&tunnels).Preload("Users").Preload("TunnelTime").Preload("Devices").Preload("Region").Error
  23. return tunnels, err
  24. }
  25. func QueryTunnelList(name string, regionId, limit, offset int) (tunnels []Tunnel, total int64, err error) {
  26. db := global.GVA_DB.Model(Tunnel{})
  27. if name != "" {
  28. db = db.Where("name LIKE ?", "%"+name+"%")
  29. }
  30. if regionId != 0 {
  31. db = db.Where("region_id = ?", regionId)
  32. }
  33. err = db.Count(&total).Error
  34. if err != nil {
  35. return
  36. }
  37. err = db.Limit(limit).Offset(offset).Preload("Users").Preload("TunnelTime").Preload("Devices").Preload("Region").Find(&tunnels).Error
  38. return
  39. }
  40. func QueryNoRegionTunnels() (tunnels []Tunnel, err error) {
  41. err = global.GVA_DB.Where("region_id =?", 0).Find(&tunnels).Error
  42. return
  43. }
  44. func (t Tunnel) CreateTunnel() error {
  45. err := global.GVA_DB.Transaction(func(tx *gorm.DB) error {
  46. err := tx.Create(&t).Error
  47. if err != nil {
  48. return err
  49. }
  50. time := TunnelTime{
  51. TunnelSn: t.TunnelSn,
  52. StartTime: "00:00",
  53. EndTime: "00:00",
  54. }
  55. err = tx.Create(&time).Error
  56. if err != nil {
  57. return err
  58. }
  59. return nil
  60. })
  61. return err
  62. }
  63. func (t Tunnel) UpdateTunnel() error {
  64. return global.GVA_DB.Where("id = ?", t.ID).Updates(&t).Error
  65. }
  66. func UpdateTunnelsRegion(tunnelIds []int, regionId int) error {
  67. return global.GVA_DB.Model(&Tunnel{}).Where("id in (?)", tunnelIds).Update("region_id", regionId).Error
  68. }
  69. func DeleteTunnel(id int) error {
  70. return global.GVA_DB.Unscoped().Where("id = ?", id).Delete(&Tunnel{}).Error
  71. }