Field
필드 이름은 Naming Convention에 따라
snake_case
로 지정해야 한다.- ID Field
- ID 필드는 스키마에 내장되어 있고, 선언하지 않아도 자동 생성된다.
- 기본적으로 Int이고, 데이터베이스에서 자동으로 증가한다.
- UUID 같이 ID 필드를 다른 타입으로 지정하고 싶으면, 다음과 같이 바꿔준다.
// Fields of the Blob.
func (Blob) Fields() []ent.Field {
return []ent.Field{
field.UUID("id", uuid.UUID{}).
Default(uuid.New).
StorageKey("oid"),
}
}
- Built-in Validators
- Numeric types:
Positive()
Negative()
NonNegative()
Min(i)
Max(i)
Range(i, j)
string
MinLen(i)
MaxLen(i)
Match(regexp.Regexp)
NotEmpty
[]byte
MaxLen(i)
MinLen(i)
NotEmpty
Immutable()
- 값을 변경할 수 없는 필드에 지정
Storage(field_name)
- 필드의 저장 이름을 명시적으로 지정
StructTag(’field:”data”’)
- struct tag 사용자 지정
Edges
- User-Pet example
- User는 여러 마리의 Pet을 갖고, Pet은 하나의 User를 가진다.
edge.To
가 선언된 스키마가 relation을 가진다.edge.From
은 relation을 소유하지 않고, 역참조만 제공한다.
// Edges of the user.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("pets", Pet.Type),
}
}
// Edges of the Pet.
func (Pet) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("pets").
Unique(),
}
}
- O2O(User-Credit Card)
// Edges of the user.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("card", Card.Type).
Unique(),
}
}
// Edges of the Card.
func (Card) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("card").
Unique().
// We add the "Required" method to the builder
// to make this edge required on entity creation.
// i.e. Card cannot be created without its owner.
Required(),
}
}
Share article