为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
富国沪深 2023-01-03 17:16:31
在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
查看完整描述

1 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

假设cat_id是一个整数(假设int64),你可以做这两件事:

  1. pagination.Cat_id字符串转换为[]int64切片(我们称此变量catIDs为 type []int64)以获取具有分隔int64元素的切片。

  2. Where将您的条款更改为如下内容:

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



查看完整回答
反对 回复 2023-01-03
  • 1 回答
  • 0 关注
  • 172 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号