2016-12-18 59 views
0

我正尝试使用orm执行操作插入。NOT NULL约束在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 
} 

回答

0

So how can I set this value to be nullable or a default value?

您可以:

  1. 从数据库中删除的not null约束,改变类型的东西,接受空值。 Go包括标准库中的一些(例如sql.Null*),但没有一个用于time.Time。写你自己的或使用像github.com/guregu/null这增加了对此的支持。
  2. 请确保在将数据插入数据库之前始终设置ReplyTime字段。

“最佳”解决方案将取决于您的应用程序以及此数据表示的内容。 ReplyTime在逻辑上是否可能具有“无价值”(例如,用户从未回复过)?如果是,则使用选项1.如果它应该始终有一个值,则使用选项2.

+0

感谢您的帮助。我对“时间”类型感到困惑,它支持可为空还是仅仅因为我将该“orm:”索引“'”添加到值中。 – machinezhou

相关问题