英文:
How to iterate over an int array in GORM
问题
在Params
模型中,我有一个整数数组Cat_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) //问题出在这里
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
英文:
In the Params
model I have an array of int Cat_id
I make a request: localhost:8080/products/?cat_id=1,2
And I want to display multiple products from these two categories. How can I parsely build my query?
My func:
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
}
When i use Debug
i got this:
SELECT * FROM "products" WHERE cat_id=(1,2) AND "products"."deleted_at" IS NULL
答案1
得分: 3
假设cat_id
是一个整数(假设为int64
),你可以进行以下两个操作:
-
将
pagination.Cat_id
字符串转换为[]int64
切片(假设将此变量命名为catIDs
,类型为[]int64
),以获得一个包含分隔的int64
元素的切片。 -
将你的
Where
子句更改为以下形式:result := config.DB.Model(&models.Products{}).Where(q).Where("cat_id IN (?)", catIDs).Limit(pagination.Limit).Offset(offset).Find(&prod)
英文:
Assuming that the cat_id
is an integer (lets assume int64
), you could these two things:
-
Convert
pagination.Cat_id
string to an[]int64
slice (lets call this variablecatIDs
of type[]int64
) to get a slice with separatedint64
elements. -
Change your
Where
clause to something like this:result := config.DB.Model(&models.Products{}).Where(q).Where("cat_id IN (?)", catIDs).Limit(pagination.Limit).Offset(offset).Find(&prod)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论