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.