Indexes can be configured on composition of fields and edges. The main use-case is setting uniqueness on fields under a specific relation. Let's take an example: 可以配置字段和边组成的索引,这主要用于确保某些关系下数据的唯一性。看一个例子:
In the example above, we have a City with many Streets, and we want to set the street name to be unique under each city. 上面的例子中,一个 City 有多条 Street, 我们想确保街道名在其所属的城市内是唯一的。
ent/schema/city.go
// City holds the schema definition for the City entity.typeCitystruct {ent.Schema}// Fields of the City.func (City) Fields() []ent.Field {return []ent.Field{ field.String("name"), }}// Edges of the City.func (City) Edges() []ent.Edge {return []ent.Edge{ edge.To("streets", Street.Type), }}
ent/schema/street.go
// Street holds the schema definition for the Street entity.typeStreetstruct {ent.Schema}// Fields of the Street.func (Street) Fields() []ent.Field {return []ent.Field{ field.String("name"), }}// Edges of the Street.func (Street) Edges() []ent.Edge {return []ent.Edge{ edge.From("city", City.Type).Ref("streets").Unique(), }}// Indexes of the Street.func (Street) Indexes() []ent.Index {return []ent.Index{ index.Fields("name").Edges("city").Unique(), }}