LoginSignup
5
4

More than 3 years have passed since last update.

Error 1292: Incorrect datetime value: '0000-00-00' に対してのGORMでの対処

Posted at

背景

Go×Ginでwebアプリケーションを作成時 userを新規登録する際に対処したことを残す。

バージョン
Go 1.13
MySQL 5.7系

起こったこと

以下のような user modelを作成

type User struct {
    UserID int64 `gorm:"primary_key" json:"user_id" form:"user_id"`

    FirstName string `gorm:"first_name" json:"first_name" form:"first_name"`

    LastName string `gorm:"last_name" json:"last_name" form:"last_name"`

    PhoneNumber string `gorm:"unique;not null" json:"phone_number" form:"phone_number"`

    Gender string `gorm:"type: enum('male', 'female', 'unspecified'); default: 'unspecified';" json:"gender" form:"gender"`

    Birthday time.Time `gorm:"birthday" json:"birthday" form:"birthday"`

    Zipcode string `gorm:"zipcode" json:"zipcode" form:"zipcode"`

    Prefecture string `gorm:"column:prefecture" json:"prefecture" form:"prefecture"`

    City string `gorm:"column:city" json:"city" form:"city"`

    AddressLine string `gorm:"column:address_line" json:"address_line" form:"address_line"`

    UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at" form:"updated_at"`

    CreatedAt time.Time `gorm:"column:created_at" json:"created_at" form:"created_at"`
}

これを利用してuserを作成する機能をgormを使用して実装していていざ実装の際に
例えば以下のような形で電話番号を持たせて新規登録する際に

    db := mysql.DB
    tx := db.Begin()

    user := models.User{PhoneNumber: phoneNumber, UpdatedAt: time.Now(), CreatedAt: time.Now()}
    fmt.Println(user)
    if err := tx.Create(&user).Error; err != nil {
        log.Fatalln(err)
        return "db"
    }

    tx.Commit()
Error 1292: Incorrect datetime value: '0000-00-00' for column 'birthday' at row 1

調べるとmysqlのsql modeの記事がたくさん出てくる

選択肢としては

該当カラムにポインタを割り当てNullをMySQLに入れる
又は
SET GLOBAL sql_mode = 'ALLOW_INVALID_DATES';

今回は開発環境だったので(今後変更はあり得る)

Birthday *time.Time `gorm:"birthday" json:"birthday" form:"birthday"`

という形で対応した。
初めてGoに触る人は引っかかるポイントだと思ったので参考になれば幸いです

参考記事

https://qiita.com/mgoldchild/items/52abb8422d62ccd9f5dc
https://www.digitalocean.com/community/tutorials/how-to-prepare-for-your-mysql-5-7-upgrade

5
4
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
5
4