entのmixinを使ってスキーマ共通の項目を設定する
Mixin
スキーマ共通の項目を定義して各スキーマで適用することが可能。
ここでは以下の記事で作成したUserテーブルに作成日時(created_at)と更新日時(updated_at)を追加する例を示す。 entを試してみた - miyazi888の覚え書き日記
共通項目の定義
ent/mixin/mixin.go
package schema import ( "time" "entgo.io/ent" "entgo.io/ent/schema/field" "entgo.io/ent/schema/mixin" ) type TimeMixin struct { mixin.Schema } func (TimeMixin) Fields() []ent.Field { return []ent.Field{ field.Time("created_at").Immutable().Default(time.Now), field.Time("updated_at").Default(time.Now()).UpdateDefault(time.Now), } }
Immutable()について
エンティティの生成時だけに設定されてほしい項目に指定する
Userテーブルに共通項目を定義
ent/schema/user.go
package schema import ( mixin "test3/ent/mixin" "entgo.io/ent" "entgo.io/ent/schema/field" ) // User holds the schema definition for the User entity. type User struct { ent.Schema } // Fields of the User. func (User) Fields() []ent.Field { return []ent.Field{ field.String("name").NotEmpty(), field.Int("age").Positive(), } } // 以下のmixinの指定を加える func (User) Mixin() []ent.Mixin { return []ent.Mixin{ mixin.TimeMixin{}, } } // Edges of the User. func (User) Edges() []ent.Edge { return nil }
コード再生成 & マイグレーション
スキーマを修正したので再生成する。
go generate ./ent
DBにも反映する。
go run migrate/migrate.go
DB上のテーブル定義を確認
docker-compose exec db /bin/sh # psql -h localhost -U user -d testdb testdb=# \d users; Table "public.users" Column | Type | Collation | Nullable | Default ------------+--------------------------+-----------+----------+---------------------------------- id | bigint | | not null | generated by default as identity name | character varying | | not null | age | bigint | | not null | created_at | timestamp with time zone | | not null | updated_at | timestamp with time zone | | not null | Indexes: "users_pkey" PRIMARY KEY, btree (id)