2016-12-18 93 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

相關問題