2
1

More than 1 year has passed since last update.

[Golang]GORMで論理削除を設定するときの注意

Last updated at Posted at 2021-09-26

はじめに

GORMの論理削除の設定にちょっとクセがあることが分かりました。

やり方

GORMはdeleted_atカラムがあれば、自動で論理削除にすることが出来ます。
しかし、型の指定でtime.Timeにするとエラーが起きます。

修正前

type Presentation struct {
    ID          int          `json:"id"`
    Title       string       `json:"title"`
    CreatedAt   time.Time    `json:"created_at"`
    DeletedAt   time.TIme    `json:"deleted_at"`
}

上記のように、time.Time型にしてしまうと、レコード作成時にデフォルトの値が入ってしまい、エラーが起きてしまいます。

修正後

type Presentation struct {
    ID          int          `json:"id"`
    Title       string       `json:"title"`
    CreatedAt   time.Time    `json:"created_at"`
    DeletedAt   sql.NullTime `json:"deleted_at"`

}

上記の用に、sql.NullTimeにすれば、レコード作成時にもNULLが入って、エラーが防げます。

参考文献

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1