2016-12-18 8 views
0

goでormを使用して操作insertを実行しようとしています。go ormでNOT NULL制約が失敗しました

私は、フィールドのような時間型の値に値を代入挿入しないでください:NOT NULL constraint failed: topic.reply_time:それはエラーがスローされます

ReplyTime  time.Time `orm:"index"` 

この値をnull値またはデフォルト値に設定するにはどうすればよいですか?

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制約を削除して、NULL値を受け入れるものに形を変えます。 Goには標準ライブラリのいくつかが含まれていますが(例:sql.Null*)、time.Timeのものはありません。あなた自身で作成するか、github.com/guregu/nullのようなものを使用してください。
  2. ReplyTimeフィールドを必ずデータベースに挿入する前に設定してください。

「最適な」ソリューションは、アプリケーションとこのデータが示すものによって異なります。論理的にはReplyTimeに「価値がない」(たとえば、ユーザーが返信しないなど)可能性がありますか?その場合は、オプション1を使用してください。値が常に必要な場合は、オプション2を使用してください。

+0

ありがとうございます。私は "time"型について混乱しています。nullableをサポートしているのでしょうか、単にこの "orm:"インデックス "' "を値に追加しているからです。 – machinezhou

関連する問題