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

出现问题:

在开发过程中,遇到这样一个问题,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)

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

产生原因:

由于在 Go 语言中,uint8 和 byte 本质上完全等同,在 GORM 和 Go 标准 database/driver 库中,对于[]byte 的处理其实和 string 类似,并不会按文中设想的将每一个[]uint8 元素当成 IN 的匹配元素 (然后用英文 , 分隔),而是将整个[]byte 当成一个匹配元素。

解决方案:

  • 方法一
    进行类型转换
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)
posted @ 2023-10-16 11:34  元気田支店长  阅读(829)  评论(0)    收藏  举报