relation.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package model
  2. import (
  3. "fmt"
  4. "sparrow/pkg/models"
  5. "github.com/jinzhu/gorm"
  6. )
  7. // Relation model
  8. type Relation struct {
  9. db *gorm.DB
  10. }
  11. // Init init Relation
  12. func (a *Relation) Init(db *gorm.DB) *Relation {
  13. a.db = db
  14. return a
  15. }
  16. // Query query all roles
  17. func (a *Relation) Query(pi, ps int, chanId string) (datas []models.Relation, total int, err error) {
  18. tx := a.db.Where("1=1")
  19. //if chanId != "" {
  20. // tx = tx.Where("rule_chain_id = ?", chanId)
  21. //}
  22. err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
  23. err = tx.Model(&models.Relation{}).Count(&total).Error
  24. return
  25. }
  26. // Get get
  27. func (a *Relation) Get(pi, ps int, chanId string) (datas []models.Relation, total int, err error) {
  28. tx := a.db.Where("1=1")
  29. if chanId != "" {
  30. tx = tx.Where("chan_id = ?", chanId)
  31. }
  32. err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
  33. err = tx.Model(&models.Relation{}).Count(&total).Error
  34. return
  35. }
  36. // Create create
  37. func (a *Relation) Create(relation *models.Relation) error {
  38. return a.db.Save(relation).Error
  39. }
  40. // Delete delete
  41. func (a *Relation) Delete(relation *models.Relation) error {
  42. cache := getCache()
  43. key := fmt.Sprintf("Relation:%d", relation.ID)
  44. if _, ok := cache.Get(key); ok {
  45. cache.Delete(key)
  46. }
  47. return a.db.Unscoped().Delete(relation).Error
  48. }
  49. //func (a *Relation) DeleteByChainId(relation *models.Relation) error {
  50. // a.db.Model(&models.Relation{}).Where("rule_chan_id = ?", relation.RuleChainId)
  51. // return a.db.Delete(relation).Error
  52. //}
  53. // Update update
  54. func (a *Relation) Update(relation *models.Relation) error {
  55. return a.db.Save(relation).Error
  56. }