Add internal/repository/shop.go
This commit is contained in:
86
internal/repository/shop.go
Normal file
86
internal/repository/shop.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"gotest/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ShopRepository 电商数据访问层
|
||||
type ShopRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewShopRepository 创建电商仓库实例
|
||||
func NewShopRepository(db *gorm.DB) *ShopRepository {
|
||||
return &ShopRepository{db: db}
|
||||
}
|
||||
|
||||
// ListCategories 获取所有分类
|
||||
func (r *ShopRepository) ListCategories() ([]model.ProductCategory, error) {
|
||||
var categories []model.ProductCategory
|
||||
if err := r.db.Order("sort ASC, id ASC").Find(&categories).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return categories, nil
|
||||
}
|
||||
|
||||
// ListProducts 获取商品列表,支持分类过滤和关键词搜索
|
||||
func (r *ShopRepository) ListProducts(categoryID uint, keyword string, sort string, page, pageSize int) ([]model.Product, int64, error) {
|
||||
var products []model.Product
|
||||
var total int64
|
||||
|
||||
query := r.db.Where("status = 1")
|
||||
if categoryID > 0 {
|
||||
query = query.Where("category_id = ?", categoryID)
|
||||
}
|
||||
if keyword != "" {
|
||||
query = query.Where("name LIKE ?", "%"+keyword+"%")
|
||||
}
|
||||
|
||||
if err := query.Model(&model.Product{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// 排序
|
||||
switch sort {
|
||||
case "price_asc":
|
||||
query = query.Order("price ASC")
|
||||
case "price_desc":
|
||||
query = query.Order("price DESC")
|
||||
case "sales":
|
||||
query = query.Order("sales DESC")
|
||||
case "rating":
|
||||
query = query.Order("rating DESC")
|
||||
default:
|
||||
query = query.Order("sort ASC, id DESC")
|
||||
}
|
||||
|
||||
if page > 0 && pageSize > 0 {
|
||||
offset := (page - 1) * pageSize
|
||||
query = query.Offset(offset).Limit(pageSize)
|
||||
}
|
||||
|
||||
if err := query.Find(&products).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return products, total, nil
|
||||
}
|
||||
|
||||
// GetProduct 根据 ID 获取商品详情
|
||||
func (r *ShopRepository) GetProduct(id uint) (*model.Product, error) {
|
||||
var product model.Product
|
||||
if err := r.db.First(&product, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &product, nil
|
||||
}
|
||||
|
||||
// ListFeaturedProducts 获取推荐商品(按销量)
|
||||
func (r *ShopRepository) ListFeaturedProducts(limit int) ([]model.Product, error) {
|
||||
var products []model.Product
|
||||
if err := r.db.Where("status = 1").Order("sales DESC").Limit(limit).Find(&products).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
Reference in New Issue
Block a user