ent 基本使用十四 edge
edge 在ent 中属于比较核心,同时也是功能最强大的,ent 提供了比较强大的关系模型
快速使用
- 参考图
以上包含了两个通过边定义的关系
pets/owner:
user
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:
group
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),
}
}
user
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(多对多)关系
To && From
edge.To和edge.From是用于创建边/关系的2个构建器。
使用edge.To构建器定义边的模式拥有该关系,与使用edge.From仅为该关系提供后向引用(使用不同名称)的构建器不同
说明
关于详细的o2o 以及M2M o2M 使用以及关系的方向可以参考官方文档
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2018-10-15 yugabyte 集成JanusGraph测试