ent 基本使用十四 edge
2024-09-04 03:34:50
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 使用以及关系的方向可以参考官方文档
参考资料
https://entgo.io/docs/schema-edges/
最新文章
- 配置gradle.properties
- JavaScript:异步 setTimeout
- (01)javascript 数据类型
- Cocos2dx Widget button透明区域过滤
- js返回上一页并刷新的多种方法
- [BZOJ 1221] [HNOI2001] 软件开发 【费用流 || 三分】
- 使用WinINet和WinHTTP实现Http訪问
- 正则表达式:根据逗号解析CSV并忽略引号内的逗号
- vs2010 调试中监视变量
- CentOS7上安装Nginx、PHP、MySQL
- 原来你是这样的setTimeout
- Html.fromHtml采坑篇
- linux下cmake安装mysql 源码
- 关于Java堆、栈和常量池的详解
- Spring 扫描标签<;context:component-scan/>;
- iOS-【最新】跳转到 App Store 评分
- 怎样为你的CSDN博客增加百度统计
- java资料——线程(转)
- 创建可复用的自定义 ASP.NET MVC Helpers
- KDD 2013推荐系统论文