我想处理将要传递的不同url参数(page
limit
cat_id
prod_id
).
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
}
当我使用Debug()查看获得了什么sql查询时,他显示了以下内容:
SELECT * FROM "products" WHERE "products"."id" IN (0,0) AND "products"."id" IN (0,1) AND "products"."deleted_at" IS NULL
他试着拿了两次Product ID
.
产品 struct :
type Products struct {
gorm.Model
CategoriesRefer int64 `json:"cat_id" gorm:"column:cat_id"`
...
}