LoginSignup
0
0

More than 3 years have passed since last update.

Gormのエンティティのiotaの扱い

Posted at

gormでiotaな型をモデルのフィールド値にしたい時

iotaのままモデルに突っ込めると定数で分岐できたり、変化球が突っ込まれることがなくなるのでiotaされている型をフィールドに定義したかった。

結論

iotaな型はゼロ値がnilとして扱われるので、gormのタグオプションのnot nullを指定してあげて、ゼロ値をnilでなく、0とさせる。またはiotaのスタートを1などにしてあげる。

↓1はじめ

type Gender int

const (
    // Male is man
    Male Gender = 1 + iota // 1
    // Female is woman
    Female // 2
)

gormエンティティ

user_info.go
// Gender is sex of human
type Gender int

const (
    // Male is man
    Male Gender = iota
    // Female is woman
    Female
)

type (
    // Info is detailed user information.
    UserInfo struct {
        common.BaseEntity // 独自定義。各エンティティの共通項を抜き出したもの
       // gormのタグオプション、not nullを指定すればok.
        Gender    Gender     `gorm:"type:tinyint(1);not null"` 
        Birthday  *time.Time `gorm:"type:datetime;default:null;"`
        LeaveDate *time.Time `gorm:"type:datetime;default:null;index:idx_leaveDate"`
    }
)

テーブル定義

user_infos.sql
-- mysql
CREATE TABLE `user_infos` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `deleted_at` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `gender` tinyint(1) NOT NULL,
  `birthday` datetime DEFAULT NULL,
  `leave_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_user_infos_deleted_at` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4;
0
0
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
0
0