package model import ( "context" "fmt" "strings" "github.com/zeromicro/go-zero/core/stores/sqlx" ) var _ UserModel = (*customUserModel)(nil) type ( // UserModel is an interface to be customized, add more methods here, // and implement the added methods in customUserModel. UserModel interface { userModel withSession(session sqlx.Session) UserModel FindList(ctx context.Context, page, pageSize int, keyword string) ([]*User, error) Count(ctx context.Context, keyword string) (int64, error) } customUserModel struct { *defaultUserModel } ) // NewUserModel returns a model for the database table. func NewUserModel(conn sqlx.SqlConn) UserModel { return &customUserModel{ defaultUserModel: newUserModel(conn), } } func (m *customUserModel) withSession(session sqlx.Session) UserModel { return NewUserModel(sqlx.NewSqlConnFromSession(session)) } // FindList 分页查询用户列表 func (m *customUserModel) FindList(ctx context.Context, page, pageSize int, keyword string) ([]*User, error) { var conditions []string var args []interface{} if keyword != "" { conditions = append(conditions, "(`username` LIKE ? OR `email` 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 ?", userRows, m.table, whereClause) var resp []*User err := m.conn.QueryRowsCtx(ctx, &resp, query, args...) return resp, err } // Count 统计用户数量 func (m *customUserModel) Count(ctx context.Context, keyword string) (int64, error) { var conditions []string var args []interface{} if keyword != "" { conditions = append(conditions, "(`username` LIKE ? OR `email` 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 }