Golang/ORM

[Entgo] About Mixin

GenieLove! 2022. 9. 1. 03:35
728x90
반응형

Mixin

  • Mixin interface를 사용하게 되면 코드를 한 번의 작성으로 재사용할 수 있다.
type Mixin interface {
    // Fields returns a slice of fields to add to the schema.
    Fields() []Field
    // Edges returns a slice of edges to add to the schema.
    Edges() []Edge
    // Indexes returns a slice of indexes to add to the schema.
    Indexes() []Index
    // Hooks returns a slice of hooks to add to the schema.
    // Note that mixin hooks are executed before schema hooks.
    Hooks() []Hook
    // Policy returns a privacy policy to add to the schema.
    // Note that mixin policy are executed before schema policy.
    Policy() Policy
    // Annotations returns a list of schema annotations to add
    // to the schema annotations.
    Annotations() []schema.Annotation
}

example

time 필드 재사용

type TimeMixin struct {
	mixin.schema
}

func (TimeMixin) Fields() []ent.Field {//mixin을 작성하므로써 중복되는 필드를 재사용할 수 있다.
	return []ent.Field{
    	field.Time("created_at").
        	Immutable().
            Default(time.Now),
        field.Time("updated_at").
        	Default(time.Now).
            UpdateDefault(time.Now),
    }
}

//-------------------------------------

func (User) Mixin() []ent.Mixin {
	return []ent.Mixin{
    	TimeMixin{},//created_at, updated_at 필드가 user테이블에 같이 추가된다.
    }
}

Builtin Mixin

mixin.Time struct를 이용할 수 있다.

mixin.Time struct는 Fields()함수에 CreatTime{}.Fields(), UpdateTime{}.Fields()를 포함하고 있어서 create_time, update_time 컬럼이 생긴다.

728x90
반응형

'Golang > ORM' 카테고리의 다른 글

[Entgo] CRUD API(작성 중)  (0) 2022.09.12
[Entgo] About Annotations  (0) 2022.09.03
[Entgo] About Indexes  (0) 2022.08.30
[Entgo] About Edges  (0) 2022.08.29
[Entgo] About Fields  (0) 2022.08.28