package model import ( "context" "fmt" "github.com/zeromicro/go-zero/core/stores/sqlx" "strings" ) var _ PhotoModel = (*customPhotoModel)(nil) type ( // PhotoModel is an interface to be customized, add more methods here, // and implement the added methods in customPhotoModel. PhotoModel interface { photoModel withSession(session sqlx.Session) PhotoModel FindList(ctx context.Context, page, pageSize int, categoryId, userId int64, keyword string) ([]*Photo, error) Count(ctx context.Context, categoryId, userId int64, keyword string) (int64, error) } customPhotoModel struct { *defaultPhotoModel } ) // NewPhotoModel returns a model for the database table. func NewPhotoModel(conn sqlx.SqlConn) PhotoModel { return &customPhotoModel{ defaultPhotoModel: newPhotoModel(conn), } } func (m *customPhotoModel) withSession(session sqlx.Session) PhotoModel { return NewPhotoModel(sqlx.NewSqlConnFromSession(session)) } // FindList 分页查询照片列表 func (m *customPhotoModel) FindList(ctx context.Context, page, pageSize int, categoryId, userId int64, keyword string) ([]*Photo, error) { var conditions []string var args []interface{} if categoryId > 0 { conditions = append(conditions, "`category_id` = ?") args = append(args, categoryId) } if userId > 0 { conditions = append(conditions, "`user_id` = ?") args = append(args, userId) } if keyword != "" { conditions = append(conditions, "(`title` 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 ?", photoRows, m.table, whereClause) var resp []*Photo err := m.conn.QueryRowsCtx(ctx, &resp, query, args...) return resp, err } // Count 统计照片数量 func (m *customPhotoModel) Count(ctx context.Context, categoryId, userId int64, keyword string) (int64, error) { var conditions []string var args []interface{} if categoryId > 0 { conditions = append(conditions, "`category_id` = ?") args = append(args, categoryId) } if userId > 0 { conditions = append(conditions, "`user_id` = ?") args = append(args, userId) } if keyword != "" { conditions = append(conditions, "(`title` 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 }