package model import ( "context" "fmt" "github.com/zeromicro/go-zero/core/stores/sqlx" "strings" ) var _ CategoryModel = (*customCategoryModel)(nil) type ( // CategoryModel is an interface to be customized, add more methods here, // and implement the added methods in customCategoryModel. CategoryModel interface { categoryModel withSession(session sqlx.Session) CategoryModel FindList(ctx context.Context, page, pageSize int, keyword string) ([]*Category, error) Count(ctx context.Context, keyword string) (int64, error) } customCategoryModel struct { *defaultCategoryModel } ) // NewCategoryModel returns a model for the database table. func NewCategoryModel(conn sqlx.SqlConn) CategoryModel { return &customCategoryModel{ defaultCategoryModel: newCategoryModel(conn), } } func (m *customCategoryModel) withSession(session sqlx.Session) CategoryModel { return NewCategoryModel(sqlx.NewSqlConnFromSession(session)) } // FindList 分页查询分类列表 func (m *customCategoryModel) FindList(ctx context.Context, page, pageSize int, keyword string) ([]*Category, error) { var conditions []string var args []interface{} if keyword != "" { conditions = append(conditions, "(`name` LIKE ? OR `description` LIKE ?)") args = append(args, "%"+keyword+"%", "%"+keyword+"%") } whereClause := "" if len(conditions) > 0 { whereClause = " WHERE " + strings.Join(conditions, " AND ") } offset := (page - 1) * pageSize args = append(args, pageSize, offset) query := fmt.Sprintf("select %s from %s%s ORDER BY `created_at` DESC LIMIT ? OFFSET ?", categoryRows, m.table, whereClause) var resp []*Category err := m.conn.QueryRowsCtx(ctx, &resp, query, args...) return resp, err } // Count 统计分类数量 func (m *customCategoryModel) Count(ctx context.Context, keyword string) (int64, error) { var conditions []string var args []interface{} if keyword != "" { conditions = append(conditions, "(`name` LIKE ? OR `description` LIKE ?)") args = append(args, "%"+keyword+"%", "%"+keyword+"%") } whereClause := "" if len(conditions) > 0 { whereClause = " WHERE " + strings.Join(conditions, " AND ") } query := fmt.Sprintf("select count(*) from %s%s", m.table, whereClause) var count int64 err := m.conn.QueryRowCtx(ctx, &count, query, args...) return count, err }