gorm 使用where in 条件查询时,使用uint8[] 类型报错的解决方案

发布时间 2023-10-16 11:38:45作者: 夕夢

出现问题:

在开发过程中,遇到这样一个问题,GORM Model 如下:

type Test struct {
	...
	
     cloumnType uint8  `gorm:"not null;default:0"`
    ...
}

其中有一个类型字段,数据范围是1-10 所以使用uint8字段来存储,在查询某些类型的数据时,使用了下面的查询语句

var list []model.Test
db.model(&model.Test{}).Where("column_type in ?",[]uint8{1,2}).Find(&list)

执行该语句后出现了如下报错

解决方案:

  • 方法一
    进行类型转换
db.model(&model.Test{}).Where("column_type in ?",cast.ToIntSlice([]uint8{1,2})).Find(&list)
  • 方法二
    加括号
db.model(&model.Test{}).Where("column_type in (?)",[]uint8{1,2}).Find(&list)