引言

概述

Schema 描述了图中一个实体类型的定义,如 UserGroup, 并可以包含以下配置:

  • 实体的字段 (或属性),如:User 的姓名或年龄。
  • 实体的边 (或关系)。如:User 所属用户组,或 User 的朋友。
  • 数据库相关的配置,如:索引或唯一索引。

下面是 Schema 的一个示例:

  1. package schema
  2. import (
  3. "entgo.io/ent"
  4. "entgo.io/ent/schema/field"
  5. "entgo.io/ent/schema/edge"
  6. "entgo.io/ent/schema/index"
  7. )
  8. type User struct {
  9. ent.Schema
  10. }
  11. func (User) Fields() []ent.Field {
  12. return []ent.Field{
  13. field.Int("age"),
  14. field.String("name"),
  15. field.String("nickname").
  16. Unique(),
  17. }
  18. }
  19. func (User) Edges() []ent.Edge {
  20. return []ent.Edge{
  21. edge.To("groups", Group.Type),
  22. edge.To("friends", User.Type),
  23. }
  24. }
  25. func (User) Indexes() []ent.Index {
  26. return []ent.Index{
  27. index.Fields("age", "name").
  28. Unique(),
  29. }
  30. }

实体 Schema 通常存储在你项目根目录的 ent/schema 目录内, 且可以通过以下的 entc 命令生成:

  1. go run -mod=mod entgo.io/ent/cmd/ent new User Group

引言 - 图1Please note, that some schema names (like Client) are not available due to internal use. You can circumvent reserved names by using an annotation as mentioned here. :::

它只是又一个 ORM

If you are used to the definition of relations over edges, that’s fine. The modeling is the same. You can model with ent whatever you can model with other traditional ORMs. There are many examples in this website that can help you get started in the Edges section.