如何使用Golang Echo框架在我的分页下创建搜索框

cuxqih21  于 2023-04-03  发布在  Go
关注(0)|答案(1)|浏览(167)
// Get page number from path `product/:page`
        pageNumber := c.Param("page")
        page, err := strconv.Atoi(pageNumber)
        if err != nil || page < 1 {
            page = 1
        }

        // set pageSize to 10 for now
        pageSize := 10

        offset := (page - 1) * pageSize

        // get the rows paginated by offset
        rows, err := database.WrapQuery(dbconnections.DBPool, ctx, "GetFromProductPaginatedByOffset", pageSize, offset)
        if err != nil {
            loggerWithTrace.Error().Err(err).Caller().Msg("database.WrapQuery error")
        }
        defer rows.Close()

        results := make([]models.Product, 0)

        for rows.Next() {
            var data models.Product
            err := rows.Scan(&data.Prefix, &data.Suffix, &data.Usage)
            if err != nil {
                loggerWithTrace.Error().Err(err).Caller().Msg("database.WrapQuery error")
            }
            results = append(results, data)
        }

        // Get the total item of product 
        var totalItems int
        err = database.WrapQueryRow(dbconnections.DBPool, ctx, "GetTotalSizeFromProduct").Scan(&totalItems)
        if err != nil {
            loggerWithTrace.Error().Err(err).Caller().Msg("database.WrapQueryRow error")
        }

        totalPages := totalItems / pageSize
        nextPage := page + 1
        prevPage := page - 1

        templateDataMap["DataMap"] = DataMap
        templateDataMap["Product"] = results
        templateDataMap["Page"] = page
        templateDataMap["PageSize"] = pageSize
        templateDataMap["TotalItems"] = totalItems
        templateDataMap["PageItemCount"] = pageSize
        templateDataMap["TotalPages"] = totalPages
        templateDataMap["NextPage"] = nextPage
        templateDataMap["PrevPage"] = prevPage

        return c.Render(http.StatusOK, "product", templateDataMap)

这里是我在handler中的分页代码,//这里有更多的代码来连接登录和cookie
这是我的SQLQ_获取分页_从_产品= SELECT * FROM PRODUCT where (prefix like '%%%s%%' or "usage" like '%%%s%%') LIMIT $1 OFFSET $2 Q_获取_从_产品_总计_大小= SELECT count(*) FROM PRODUCT
这是我的路由PATH_PAGINATE_PRODUCT = PATH +“/product/:page”

例如GET(PATH_PAGINATE_PRODUCT,handlers.Product)

我试图创建搜索框/搜索查询,但它似乎没有工作

rvpgvaaj

rvpgvaaj1#

在SQL查询前缀和用法的LIKE运算符中,必须传递参数,如下例所示

//... some logic
// change your request like this
prefix = "%"+data.Prefix+"%"
usage = "%"+data.Usage+"%"

然后SQL查询必须更改为

SELECT * FROM PRODUCT where (prefix like '%s' or "usage" like '%s') LIMIT $1 OFFSET $2

相关问题