feat:add conds

This commit is contained in:
Rogee
2025-05-06 10:01:48 +08:00
parent 12e1a18d89
commit 35fdca71e5
6 changed files with 97 additions and 71 deletions

View File

@@ -6,6 +6,7 @@ import (
"time"
"quyun/app/requests"
"quyun/database/conds"
"quyun/database/schemas/public/model"
"quyun/database/schemas/public/table"
@@ -25,39 +26,15 @@ func (m *postsModel) Prepare() error {
return nil
}
// BuildConditionWithKey
func (m *postsModel) BuildConditionWithKey(key *string) BoolExpression {
tbl := table.Posts
cond := tbl.DeletedAt.IS_NULL()
if key == nil || *key == "" {
return cond
}
cond = cond.AND(
tbl.Title.LIKE(String("%" + *key + "%")).
OR(
tbl.Content.LIKE(String("%" + *key + "%")),
).
OR(
tbl.Description.LIKE(String("%" + *key + "%")),
),
)
return cond
}
// GetByID
func (m *postsModel) GetByID(ctx context.Context, id int64) (*model.Posts, error) {
func (m *postsModel) GetByID(ctx context.Context, id int64, cond ...conds.Cond) (*model.Posts, error) {
tbl := table.Posts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(
tbl.ID.EQ(Int64(id)).AND(
tbl.DeletedAt.IS_NULL(),
),
)
var combinedCond BoolExpression = tbl.ID.EQ(Int64(id))
for _, c := range cond {
combinedCond = c(combinedCond)
}
stmt := tbl.SELECT(tbl.AllColumns).WHERE(combinedCond)
m.log.Infof("sql: %s", stmt.DebugSql())
var post model.Posts
@@ -121,13 +98,18 @@ func (m *postsModel) countByCondition(ctx context.Context, expr BoolExpression)
return cnt.Cnt, nil
}
func (m *postsModel) List(ctx context.Context, pagination *requests.Pagination, cond BoolExpression, callbacks ...func(model.Posts) model.Posts) (*requests.Pager, error) {
func (m *postsModel) List(ctx context.Context, pagination *requests.Pagination, cond ...conds.Cond) (*requests.Pager, error) {
pagination.Format()
combinedCond := table.Posts.DeletedAt.IS_NULL()
for _, c := range cond {
combinedCond = c(combinedCond)
}
tbl := table.Posts
stmt := tbl.
SELECT(tbl.AllColumns).
WHERE(cond).
WHERE(combinedCond).
ORDER_BY(tbl.ID.DESC()).
LIMIT(pagination.Limit).
OFFSET(pagination.Offset)
@@ -140,20 +122,12 @@ func (m *postsModel) List(ctx context.Context, pagination *requests.Pagination,
return nil, err
}
count, err := m.countByCondition(ctx, cond)
count, err := m.countByCondition(ctx, combinedCond)
if err != nil {
m.log.Errorf("error getting post count: %v", err)
return nil, err
}
if len(callbacks) > 0 {
for _, f := range callbacks {
posts = lo.Map(posts, func(item model.Posts, _ int) model.Posts {
return f(item)
})
}
}
return &requests.Pager{
Items: posts,
Total: count,