mysql - 在 mysql 中使用 gorm 插入键入的 []byte 引发“错误 1241:操作数应包含 1 列”
问题描述
我有一个带有类型[]byte
(密码哈希)的模型,我想MySQL:5.7
使用gorm:v2
.
// this will work
type ModelRaw struct {
Bytes []byte
}
type Hash []byte
// this will NOT work
type ModelTyped struct {
Bytes Hash
}
func main() {
// Migrate database
// Both tables will have a column `bytes` of type `longblob default:NULL`
if err := gormDB.AutoMigrate(&ModelRaw{}, &ModelTyped{}); err != nil {
panic(err)
}
// this works
mdl1 := &ModelRaw{Bytes: []byte("random-bytes")}
if err := gormDB.Debug().Create(mdl1).Error; err != nil {
panic(err)
}
// error here
mdl2 := &ModelTyped{Bytes: Hash("random-bytes")}
if err := gormDB.Debug().Create(mdl2).Error; err != nil {
panic(err)
}
}
上面的代码导致以下gorm
调试输出:
2020/11/06 10:31:29 /go/src/app/main.go:47
[7.715ms] [rows:1] INSERT INTO `model_raws` (`bytes`) VALUES ('random-bytes')
2020/11/06 10:31:29 /go/src/app/main.go:53 Error 1241: Operand should contain 1 column(s)
[0.926ms] [rows:0] INSERT INTO `model_typeds` (`bytes`) VALUES ((114,97,110,100,111,109,45,98,121,116,101,115))
panic: Error 1241: Operand should contain 1 column(s)
演示问题的回购:https ://github.com/Iyashi/go-gorm-bytes-test
它工作 gorm:v1
并闯入gorm:v2
。
gorm 的 AutoMigrate() 将 mysql 表列创建为longblob NULL
.
解决方案
为此,您应该只实现一个 driver.Valuer 接口:
func (h Hash) Value() (driver.Value, error) {
return []byte(h), nil
}
然后您输入的数据将按预期与 Gorm v2 一起使用。
推荐阅读
- javascript - React Native - 无法启动,因为 HTTP 服务器已被另一个 WebSocket 服务器使用
- c# - 如何使 foreach() 仅迭代前 3 个条目?
- node.js - 如何仅在服务器批准后接受multer上传?
- javascript - 敲除 bindingHandler 导致 pureComputed 评估延迟
- excel - Excel 动态数组溢出区域 - 它可以沿着一行还是沿着一列?
- go - 如何发出 HTTP 发布数据请求
- php - 无法连接到数据库(HY000/1045),尝试使用 php mysqli_connection 连接到数据库
- php - PHP:如何替换特定数据?
- java - 给定一个数字,打印接下来的三个数字
- firebase - 没有 Cocoa Pod 的 tvOS 的 Firebase