edge 在ent 中属于比较核心,同时也是功能最强大的,ent 提供了比较强大的关系模型git
以上包含了两个经过边定义的关系
pets/owner:
usergithub
package schema
import (
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/schema/edge"
)
// User schema.
type User struct {
ent.Schema
}
// Fields of the user.
func (User) Fields() []ent.Field {
return []ent.Field{
// ...
}
}
// Edges of the user.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("pets", Pet.Type),
}
}
pet架构
package schema
import (
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/schema/edge"
)
// User schema.
type Pet struct {
ent.Schema
}
// Fields of the user.
func (Pet) Fields() []ent.Field {
return []ent.Field{
// ...
}
}
// Edges of the user.
func (Pet) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("pets").
Unique(),
}
}
说明:
如您所见,一个User实体能够拥有宠物,可是一个Pet实体只能拥有一我的。
在关系定义中,pets边是O2M(一对多)关系,owner边是M2O(多对一)关系。
该User schema 拥有该pets/owner关系,由于它使用edge.To,而且该Pet schema 仅具备使用edge.From该Ref方法声明的对其的反向引用。
该Ref方法描述了User咱们要引用的架构的哪一个边,由于从一个架构到另外一个架构能够有多个引用。
边/关系的基数能够使用该Unique方法进行控制,下面将对其进行更普遍的说明。
users / groups:
groupspa
package schema
import (
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/schema/edge"
)
// Group schema.
type Group struct {
ent.Schema
}
// Fields of the group.
func (Group) Fields() []ent.Field {
return []ent.Field{
// ...
}
}
// Edges of the group.
func (Group) Edges() []ent.Edge {
return []ent.Edge{
edge.To("users", User.Type),
}
}
usercode
package schema
import (
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/schema/edge"
)
// User schema.
type User struct {
ent.Schema
}
// Fields of the user.
func (User) Fields() []ent.Field {
return []ent.Field{
// ...
}
}
// Edges of the user.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.From("groups", Group.Type).
Ref("users"),
// "pets" declared in the example above.
edge.To("pets", Pet.Type),
}
}
说明:
能够看到,一个组实体能够有许多用户,一个用户实体能够有许多组。
在关系定义中,users边是M2M(多对多)关系,groups 边也是M2M(多对多)关系blog
edge.To和edge.From是用于建立边/关系的2个构建器。
使用edge.To构建器定义边的模式拥有该关系,与使用edge.From仅为该关系提供后向引用(使用不一样名称)的构建器不一样ip
关于详细的o2o 以及M2M o2M 使用以及关系的方向能够参考官方文档文档