如何在GORM中迭代int数组



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(,您可以得到以下两件事:

  1. pagination.Cat_id字符串转换为[]int64切片(让我们调用[]int64类型的变量catIDs(,以获得具有分离的int64元素的切片。

  2. Where子句更改为以下内容:

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

最新更新