实现category service基础接口

This commit is contained in:
2025-05-31 16:27:01 +08:00
parent faa6a35475
commit e5446bf836
33 changed files with 1420 additions and 67 deletions

View File

@ -3,6 +3,7 @@ package model
import (
"context"
"github.com/Masterminds/squirrel"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
@ -17,6 +18,11 @@ type (
Transact(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error
FindBySystemParentName(ctx context.Context, systemID string, parentID string, name string) (*Categories, error)
FindBySystemParentAlias(ctx context.Context, systemID string, parentID string, alias string) (*Categories, error)
// 新增方法
RowBuilder() squirrel.SelectBuilder
FindCount(ctx context.Context, builder squirrel.SelectBuilder) (int64, error)
FindAll(ctx context.Context, builder squirrel.SelectBuilder) ([]*Categories, error)
}
customCategoriesModel struct {
@ -72,3 +78,81 @@ func (m *customCategoriesModel) FindBySystemParentAlias(ctx context.Context, sys
}
return &resp, nil
}
// === 新增方法实现 ===
// RowBuilder 创建一个基本的SELECT查询构建器
func (m *customCategoriesModel) RowBuilder() squirrel.SelectBuilder {
return squirrel.Select(categoriesRows).From(m.table)
}
// FindCount 执行COUNT查询
func (m *customCategoriesModel) FindCount(ctx context.Context, builder squirrel.SelectBuilder) (int64, error) {
// 将SELECT转换为COUNT
builder = builder.Columns("COUNT(1) AS count")
query, args, err := builder.ToSql()
if err != nil {
return 0, err
}
var count int64
err = m.conn.QueryRowCtx(ctx, &count, query, args...)
if err != nil {
return 0, err
}
return count, nil
}
// FindAll 执行查询并返回所有结果
func (m *customCategoriesModel) FindAll(ctx context.Context, builder squirrel.SelectBuilder) ([]*Categories, error) {
query, args, err := builder.ToSql()
if err != nil {
return nil, err
}
var categories []*Categories
err = m.conn.QueryRowsCtx(ctx, &categories, query, args...)
if err != nil && err != sqlx.ErrNotFound {
return nil, err
}
return categories, nil
}
// === 辅助函数 ===
// 添加分页支持
func (m *customCategoriesModel) FindAllWithPagination(
ctx context.Context,
builder squirrel.SelectBuilder,
orderBy string,
page int,
pageSize int,
) ([]*Categories, int64, error) {
// 获取总数
total, err := m.FindCount(ctx, builder)
if err != nil {
return nil, 0, err
}
// 添加分页
if page > 0 && pageSize > 0 {
offset := (page - 1) * pageSize
builder = builder.Offset(uint64(offset)).Limit(uint64(pageSize))
}
// 添加排序
if orderBy != "" {
builder = builder.OrderBy(orderBy)
}
// 执行查询
categories, err := m.FindAll(ctx, builder)
if err != nil {
return nil, 0, err
}
return categories, total, nil
}