How to iterate over an int array in GORM

huangapple go评论90阅读模式
英文:

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),你可以进行以下两个操作:

  1. pagination.Cat_id字符串转换为[]int64切片(假设将此变量命名为catIDs,类型为[]int64),以获得一个包含分隔的int64元素的切片。

  2. 将你的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:

  1. Convert pagination.Cat_id string to an []int64 slice (lets call this variable catIDs of type []int64) to get a slice with separated int64 elements.

  2. 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)
    

huangapple
  • 本文由 发表于 2022年7月24日 22:56:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/73099470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定