tianyuan-api-server/apps/sentinel/internal/model/productsmodel.go
2024-10-16 20:46:46 +08:00

93 lines
2.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package model
import (
"context"
"fmt"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx"
"strings"
)
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, filter *ProductFilter) ([]*Products, int64, error)
}
customProductsModel struct {
*defaultProductsModel
}
)
// NewProductsModel returns a model for the database table.
func NewProductsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) ProductsModel {
return &customProductsModel{
defaultProductsModel: newProductsModel(conn, c, opts...),
}
}
func (m *defaultProductsModel) FindProductsList(ctx context.Context, page, pageSize int64, filter *ProductFilter) ([]*Products, int64, error) {
offset := (page - 1) * pageSize
var products []*Products
// 构建筛选条件
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 %s", m.table, whereClause)
err = m.QueryRowNoCacheCtx(ctx, &total, countQuery, args[:len(args)-2]...)
if err != nil {
return nil, 0, err
}
return products, total, nil
}