英文:
NOT NULL constraint failed in go orm
问题
我正在尝试使用Go语言中的ORM执行插入操作。
我执行插入操作时,对于时间类型的字段,我没有为其赋值,例如:
ReplyTime time.Time `orm:"index"`
这将抛出错误:NOT NULL constraint failed: topic.reply_time
。
那么我该如何将该值设置为可为空或默认值?
type Topic struct {
Id int64
UId int64
Title string
Content string `orm:"size(5000)"`
Attachment string
Created time.Time `orm:"index"`
Updated time.Time `orm:"index"`
Views int64 `orm:"index"`
Author string
ReplyTime time.Time `orm:"index"`
ReplyCount int64
ReplyLastUserId int64
}
func AddTopic(title, content string) error {
o := orm.NewOrm()
t := time.Now()
topic := &Topic{Title:title, Content:content, Created:t, Updated:t}
_, err := o.Insert(topic)
return err
}
英文:
I'm trying to execute operation insert with orm in go.
I do insert and not assign value to time type value like the field:
ReplyTime time.Time `orm:"index"`
it will throw error: NOT NULL constraint failed: topic.reply_time
.
So how can I set this value to be nullable or a default value?
type Topic struct {
Id int64
UId int64
Title string
Content string `orm:"size(5000)"`
Attachment string
Created time.Time `orm:"index"`
Updated time.Time `orm:"index"`
Views int64 `orm:"index"`
Author string
ReplyTime time.Time `orm:"index"`
ReplyCount int64
ReplyLastUserId int64
}
func AddTopic(title, content string) error {
o := orm.NewOrm()
t := time.Now()
topic := &Topic{Title:title, Content:content, Created:t, Updated:t}
_, err := o.Insert(topic)
return err
}
答案1
得分: 0
如何将该值设置为可为空或默认值?
你可以选择以下方法之一:
- 从数据库中删除
not null
约束,并将类型更改为接受空值的类型。Go语言的标准库中包含了一些这样的类型(例如sql.Null*
),但对于time.Time
类型并没有提供。你可以自己编写一个类型,或者使用github.com/guregu/null
这样的库来添加对此的支持。 - 确保在将
ReplyTime
字段插入数据库之前始终设置其值。
"最佳"解决方案将取决于你的应用程序以及这个数据的含义。ReplyTime
是否可以在逻辑上"没有值"(例如用户从未回复)?如果是这样,那么使用选项1。如果它应该始终有一个值,那么使用选项2。
英文:
> So how can I set this value to be nullable or a default value?
You can either:
- Remove the
not null
constraint from the database and change the type to something that accepts null values. Go includes a few of those in the standard library (e.g.sql.Null*
) but doesn't have one fortime.Time
. Write your own or use something likegithub.com/guregu/null
which adds support for this. - Make sure you always set the
ReplyTime
field before inserting it in the database.
The "best" solution will depend on your application and what this data signifies. Should it be logically possible for ReplyTime
to have "no value" (e.g. user never replied)? If so, then use option 1. If it should always have a value, then use option 2.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论