This commit is contained in:
2024-10-16 20:46:46 +08:00
parent fdfdbb5ff6
commit 185b8aef90
14 changed files with 546 additions and 306 deletions

View File

@@ -12,12 +12,18 @@ import (
var _ ProductsModel = (*customProductsModel)(nil)
var productsRowsWithoutContent = strings.Join(stringx.Remove(productsFieldNames, "`ProductContent`"), ",")
type ProductFilter struct {
ProductName string // 产品名称,模糊匹配
ProductGroup string // 产品分类,模糊匹配
IsEnabled *int64 // 是否启用1-启用0-禁用,使用指针类型来区分是否需要筛选
IsVisible *int64 // 是否展示1-展示0-隐藏,使用指针类型来区分是否需要筛选
}
type (
// ProductsModel is an interface to be customized, add more methods here,
// and implement the added methods in customProductsModel.
ProductsModel interface {
productsModel
FindProductsList(ctx context.Context, page, pageSize int64) ([]*Products, int64, error)
FindProductsList(ctx context.Context, page, pageSize int64, filter *ProductFilter) ([]*Products, int64, error)
}
customProductsModel struct {
@@ -31,20 +37,53 @@ func NewProductsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option
defaultProductsModel: newProductsModel(conn, c, opts...),
}
}
func (m *defaultProductsModel) FindProductsList(ctx context.Context, page, pageSize int64) ([]*Products, int64, error) {
func (m *defaultProductsModel) FindProductsList(ctx context.Context, page, pageSize int64, filter *ProductFilter) ([]*Products, int64, error) {
offset := (page - 1) * pageSize
var products []*Products
query := fmt.Sprintf("SELECT %s FROM %s ORDER BY created_at DESC LIMIT ?,?", productsRowsWithoutContent, m.table)
err := m.QueryRowsNoCacheCtx(ctx, &products, query, offset, pageSize)
// 构建筛选条件
var conditions []string
var args []interface{}
if filter.ProductName != "" {
conditions = append(conditions, "product_name LIKE ?")
args = append(args, "%"+filter.ProductName+"%")
}
if filter.ProductGroup != "" {
conditions = append(conditions, "product_group LIKE ?")
args = append(args, "%"+filter.ProductGroup+"%")
}
// 如果明确传入启用状态为 0 或 1 则筛选,否则跳过筛选
if filter.IsEnabled != nil {
conditions = append(conditions, "is_enabled = ?")
args = append(args, *filter.IsEnabled)
}
// 如果明确传入展示状态为 0 或 1 则筛选,否则跳过筛选
if filter.IsVisible != nil {
conditions = append(conditions, "is_visible = ?")
args = append(args, *filter.IsVisible)
}
whereClause := ""
if len(conditions) > 0 {
whereClause = "WHERE " + strings.Join(conditions, " AND ")
}
// 查询产品列表
query := fmt.Sprintf("SELECT %s FROM %s %s ORDER BY created_at DESC LIMIT ?,?", productsRows, m.table, whereClause)
args = append(args, offset, pageSize)
err := m.QueryRowsNoCacheCtx(ctx, &products, query, args...)
if err != nil {
return nil, 0, err
}
// 查询总数量
var total int64
countQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s", m.table)
err = m.QueryRowNoCacheCtx(ctx, &total, countQuery)
countQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s %s", m.table, whereClause)
err = m.QueryRowNoCacheCtx(ctx, &total, countQuery, args[:len(args)-2]...)
if err != nil {
return nil, 0, err
}