ent 基本使用五 schema介绍

ent 提供了自动生成schema 但是,我们可以基于生成schema 进行扩展,schema 主要包含以下配置

  • 实体的字段(或者属性)比如 user 的name 以及age
  • 实体的边(关系),比如user 的groups user 的friends
  • 数据库选项,所以以及唯一索引

一个简单的schema

package schema
import (
    "github.com/facebookincubator/ent"
    "github.com/facebookincubator/ent/schema/field"
    "github.com/facebookincubator/ent/schema/edge"
    "github.com/facebookincubator/ent/schema/index"
)
type User struct {
    ent.Schema
}
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.Int("age"),
        field.String("name"),
        field.String("nickname").
            Unique(),
    }
}
func (User) Edges() []ent.Edge {
    return []ent.Edge{
        edge.To("groups", Group.Type),
        edge.To("friends", User.Type),
    }
}
func (User) Index() []ent.Index {
    return []ent.Index{
        index.Fields("age", "name").
            Unique(),
    }
}
 

说明

ent 提供了一个命令行工具,我们可以用来生成schema

entc init User Group

附带ent 命令行工具的帮助

Usage:
  entc [command]
Available Commands:
  describe print a description of the graph schema
  generate generate go code for the schema directory
  help Help about any command
  init initialize an environment with zero or more schemas
Flags:
  -h, --help help for entc
Use "entc [command] --help" for more information about a command.
 
 

参考资料

https://entgo.io/docs/schema-def/

posted on   荣锋亮  阅读(737)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2016-10-14 既使用maven又使用本地Jar包

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示