在Params
模型中,我有一个intCat_id
数组
我提出一个请求:localhost:8080/products/?cat_id=1,2
我想展示这两个类别中的多个产品。如何解析构建查询?我的功能:
func GetAllIproducts(q *models.Products, pagination *models.Params) (*[]models.Products, error) {
var prod []models.Products
offset := (pagination.Page - 1) * pagination.Limit
result := config.DB.Model(&models.Products{}).Where(q).Where("cat_id=?", pagination.Cat_id).Limit(pagination.Limit).Offset(offset).Find(&prod) //Problem is here
if result.Error != nil {
msg := result.Error
return nil, msg
}
return &prod, nil
}
当我使用Debug
时,我得到了:SELECT * FROM "products" WHERE cat_id=(1,2) AND "products"."deleted_at" IS NULL
假设cat_id
是一个整数(假设int64
(,您可以得到以下两件事:
-
将
pagination.Cat_id
字符串转换为[]int64
切片(让我们调用[]int64
类型的变量catIDs
(,以获得具有分离的int64
元素的切片。 -
将
Where
子句更改为以下内容:result := config.DB.Model(&models.Products{}).Where(q).Where("cat_id IN (?)", catIDs).Limit(pagination.Limit).Offset(offset).Find(&prod)