Home > Mobile >  How to get multiple url params values
How to get multiple url params values

Time:07-23

I want to handle different url parameters (page, limit, cat_id, prod_id) that will be passed. I have 2 funcs:

func GeneratePaginationFromRequest(c *gin.Context) models.Pagination {
    limit := 0
    page := 1
    prod_id := 0
    cat_id := 0
    query := c.Request.URL.Query()
    for key, value := range query {
        queryValue := value[len(value)-1]
        switch key {
        case "limit":
            limit, _ = strconv.Atoi(queryValue)
        case "page":
            page, _ = strconv.Atoi(queryValue)
        case "cat_id":
            cat_id, _ = strconv.Atoi(queryValue)
        case "prod_id":
            prod_id, _ = strconv.Atoi(queryValue)
        }
    }
    return models.Pagination{
        Limit:   limit,
        Page:    page,
        Cat_id:  cat_id,
        Prod_id: prod_id,
    }
}
func GetAllIproducts(q *models.Products, pagination *models.Pagination) (*[]models.Products, error) {
    var prod []models.Products
    offset := (pagination.Page - 1) * pagination.Limit
    queryBuider := config.DB.Limit(pagination.Limit).Offset(offset)
    result := queryBuider.Model(&models.Products{}).Where(q.ID, pagination.Prod_id).Where(q.CategoriesRefer, pagination.Cat_id).Find(&prod)
    if result.Error != nil {
        msg := result.Error
        return nil, msg
    }
    return &prod, nil
}

When i use Debug() to see what sql query is obtained, he displays this:

SELECT * FROM "products" WHERE "products"."id" IN (0,0) AND "products"."id" IN (0,1) AND "products"."deleted_at" IS NULL

He tries to take Product ID twice.

Product struct:

type Products struct {
    gorm.Model
    CategoriesRefer   int64      `json:"cat_id" gorm:"column:cat_id"`
    ...
}

CodePudding user response:

Instead of this:

result := queryBuider.Model(&models.Products{}).Where(q.ID, pagination.Prod_id).Where(q.CategoriesRefer, pagination.Cat_id).Find(&prod)

Try this:

result := config.DB.Debug().Model(&models.Products{}).Where(q).Where("cat_id=?", pagination.Cat_id).Where("prod_id=?", pagination.Prod_id).Limit(pagination.Limit).Offset(offset).Find(&prod)


  • Related