123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- package model
- import (
- "fmt"
- "sparrow/pkg/models"
- "github.com/jinzhu/gorm"
- )
- // Product ``
- type Product struct {
- db *gorm.DB
- }
- // Init 初始化
- func (a *Product) Init(_db *gorm.DB) *Product {
- a.db = _db
- return a
- }
- //Create 添加
- func (a *Product) Create(product *models.Product) error {
- cache := getCache()
- key := fmt.Sprintf("Product:%s", product.ProductKey)
- cache.Set(key, product)
- return a.db.Save(product).Error
- }
- // Delete 删除
- func (a *Product) Delete(product *models.Product) error {
- cache := getCache()
- key := fmt.Sprintf("Product:%s", product.ProductKey)
- if _, ok := cache.Get(key); ok {
- cache.Delete(key)
- }
- return a.db.Delete(product).Error
- }
- // Update 更新
- func (a *Product) Update(product *models.Product) (pro models.Product, err error) {
- cache := getCache()
- key := fmt.Sprintf("Product:%s", product.ProductKey)
- if _, ok := cache.Get(key); ok {
- cache.Delete(key)
- }
- cache.Set(key, product)
- err = a.db.Model(&pro).Update(product).Error
- return
- }
- // GetVendorProducts 获取厂商的产品列表
- func (a *Product) GetVendorProducts(vendorid uint, pi, ps int, name string) (datas []models.Product, total int, err error) {
- tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
- if name != "" {
- tx = tx.Where("product_name like ?", "%"+name+"%")
- }
- err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
- tx.Model(&models.Product{}).Count(&total)
- return
- }
- // QueryOne 获取单个产品内容
- func (a *Product) QueryOne(productkey string, vendorid uint) (data models.Product, err error) {
- cache := getCache()
- key := fmt.Sprintf("Product:%s", productkey)
- if v, ok := cache.Get(key); ok {
- _d := v.(*models.Product)
- data = *_d
- } else {
- err = a.db.Where("vendor_id = ? and product_key = ?", vendorid, productkey).First(&data).Error
- cache.Set(key, &data)
- }
- return
- }
|