如何在 GORM 中迭代一个 int 数组

在Params模型中我有一个 int 数组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) //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


富国沪深
浏览 173回答 1
1回答

慕标5832272

假设cat_id是一个整数(假设int64),你可以做这两件事:将pagination.Cat_id字符串转换为[]int64切片(我们称此变量catIDs为 type []int64)以获取具有分隔int64元素的切片。Where将您的条款更改为如下内容: result := config.DB.Model(&models.Products{}).Where(q).Where("cat_id IN (?)", catIDs).Limit(pagination.Limit).Offset(offset).Find(&prod)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go