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
CodePudding user response:
Assuming that the cat_id
is an integer (lets assume int64
), you could these two things:
Convert
pagination.Cat_id
string to an[]int64
slice (lets call this variablecatIDs
of type[]int64
) to get a slice with separatedint64
elements.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)