英文:
Insert a piece of data into mysql by using gorm
问题
我想将一条数据插入到我的数据库(MySQL)中,但是失败了。
错误1364:字段'envelopeId'没有默认值。
我发现有些人说这是因为主键是int类型,并且没有设置为自动递增,但实际上它是varchar类型。
var envelope Envelope
envelope = Envelope{
"100000000001",
1,
0,
100,
}
fmt.Println(db.Create(&envelope).Error)
英文:
I want to insert a piece of data into my database(MySQL). However, I failed.
Error 1364: Field 'envelopeId' doesn't have a default value.
I found that some people say that this is because the primary key is of int type and not set to auto-increment, but this is actually a varchar type.
var envelope Envelope
envelope = Envelope{
"100000000001",
1,
0,
100,
}
fmt.Println(db.Create(&envelope).Error)
答案1
得分: 1
这个错误意味着你正在尝试将一个NULL
值插入到一个非空字段中,而且由于没有指定默认值,所以会报错。我猜"100000000001"
是你的主键,如果是这样的话,你需要检查结构体中是否设置了该字段的gorm:"column:envelopeId"
标签。根据GORM的约定,列名应该使用蛇形命名法,而不是你在数据库中使用的驼峰命名法。
英文:
This error means that you are trying to insert an NULL
value into a non-nullable field, and since there is also no default value specified it gives you and error. I assume "100000000001"
is your primary key, if this is the case, it is set in your struct and you need to check that that field has the gorm:"column:envelopeId"
tag set. By convention GORM will use snake case for column names, not camel case like you have in your DB.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论