product.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. err := a.db.Save(product).Error
  21. if err == nil {
  22. cache.Set(key, product)
  23. }
  24. return err
  25. }
  26. // Delete 删除
  27. func (a *Product) Delete(product *models.Product) error {
  28. cache := getCache()
  29. key := fmt.Sprintf("Product:%s", product.ProductKey)
  30. if _, ok := cache.Get(key); ok {
  31. cache.Delete(key)
  32. }
  33. return a.db.Delete(product).Error
  34. }
  35. // Update 更新
  36. func (a *Product) Update(product *models.Product) (pro models.Product, err error) {
  37. err = a.db.Model(&pro).Save(product).Error
  38. if err == nil {
  39. cache := getCache()
  40. key := fmt.Sprintf("Product:%s", product.ProductKey)
  41. if _, ok := cache.Get(key); ok {
  42. cache.Delete(key)
  43. }
  44. cache.Set(key, product)
  45. }
  46. return
  47. }
  48. // GetVendorProducts 获取厂商的产品列表
  49. func (a *Product) GetVendorProducts(vendorid string, pi, ps int, name string) (datas []models.Product, total int, err error) {
  50. tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
  51. if name != "" {
  52. tx = tx.Where("product_name like ?", "%"+name+"%")
  53. }
  54. err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
  55. tx.Model(&models.Product{}).Count(&total)
  56. return
  57. }
  58. // QueryOne 获取单个产品内容
  59. func (a *Product) QueryOne(productkey string, vendorid string) (data models.Product, err error) {
  60. cache := getCache()
  61. key := fmt.Sprintf("Product:%s", productkey)
  62. if v, ok := cache.Get(key); ok {
  63. _d := v.(*models.Product)
  64. data = *_d
  65. } else {
  66. err = a.db.Where("vendor_id = ? and product_key = ?", vendorid, productkey).First(&data).Error
  67. cache.Set(key, &data)
  68. }
  69. return
  70. }