product.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package model
  2. import (
  3. "fmt"
  4. "sparrow/pkg/models"
  5. "github.com/jinzhu/gorm"
  6. )
  7. // Product ``
  8. type Product struct {
  9. db *gorm.DB
  10. }
  11. // Init 初始化
  12. func (a *Product) Init(_db *gorm.DB) *Product {
  13. a.db = _db
  14. return a
  15. }
  16. //Create 添加
  17. func (a *Product) Create(product *models.Product) error {
  18. cache := getCache()
  19. key := fmt.Sprintf("Product:%s", product.ProductKey)
  20. cache.Set(key, product)
  21. return a.db.Save(product).Error
  22. }
  23. // Delete 删除
  24. func (a *Product) Delete(product *models.Product) error {
  25. cache := getCache()
  26. key := fmt.Sprintf("Product:%s", product.ProductKey)
  27. if _, ok := cache.Get(key); ok {
  28. cache.Delete(key)
  29. }
  30. return a.db.Delete(product).Error
  31. }
  32. // Update 更新
  33. func (a *Product) Update(product *models.Product) (pro models.Product, err error) {
  34. cache := getCache()
  35. key := fmt.Sprintf("Product:%s", product.ProductKey)
  36. if _, ok := cache.Get(key); ok {
  37. cache.Delete(key)
  38. }
  39. cache.Set(key, product)
  40. err = a.db.Model(&pro).Update(product).Error
  41. return
  42. }
  43. // GetVendorProducts 获取厂商的产品列表
  44. func (a *Product) GetVendorProducts(vendorid uint, pi, ps int, name string) (datas []models.Product, total int, err error) {
  45. tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
  46. if name != "" {
  47. tx = tx.Where("product_name like ?", "%"+name+"%")
  48. }
  49. err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
  50. tx.Model(&models.Product{}).Count(&total)
  51. return
  52. }
  53. // QueryOne 获取单个产品内容
  54. func (a *Product) QueryOne(productkey string, vendorid uint) (data models.Product, err error) {
  55. cache := getCache()
  56. key := fmt.Sprintf("Product:%s", productkey)
  57. if v, ok := cache.Get(key); ok {
  58. _d := v.(*models.Product)
  59. data = *_d
  60. } else {
  61. err = a.db.Where("vendor_id = ? and product_key = ?", vendorid, productkey).First(&data).Error
  62. cache.Set(key, &data)
  63. }
  64. return
  65. }