Introduction

Quick Summary

Schema describes the definition of one entity type in the graph, like User or Group, and can contain the following configurations:

  • Entity fields (or properties), like: name or age of a User.
  • Entity edges (or relations), like: User‘s groups, or User‘s friends.
  • Database specific options, like: indexes or unique indexes.

Here’s an example of a 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. }

Entity schemas are usually stored inside ent/schema directory under the root directory of your project, and can be generated by entc as follows:

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

Introduction - 图1note

Please 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.

It’s Just Another 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.