登录
首页 >  Golang >  Go问答

在 GORM 中如何对 int 数组进行遍历

来源:stackoverflow

时间:2024-02-19 08:36:23 220浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《在 GORM 中如何对 int 数组进行遍历》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

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


正确答案


假设 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)

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 GORM 中如何对 int 数组进行遍历》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>