跳到主要内容

注解

模式注解允许为字段和边等模式对象附加元数据,并将这些数据注入外部模板。注解必须是可序列化为 JSON 原始值的 Go 语言类型(例如结构体、映射或切片),并实现 Annotation 接口。

内置注解支持配置不同的存储驱动程序(如SQL)并控制代码生成输出。

自定义表名

使用 entsql 注解可以允许提供自定义表名:

ent/schema/user.go
package schema

import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}

// Annotations of the User.
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "Users"},
}
}

// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.Int("age"),
field.String("name"),
}
}

自定义表模式

使用 Atlas 迁移引擎,Ent 模式可以在多个数据库模式之间定义和管理。查阅 多模式文档 了解更多信息。

外键配置

Ent 允许自定义外键创建,并为 ON DELETE 子句提供引用操作

ent/schema/user.go
package schema

import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Default("Unknown"),
}
}

// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("posts", Post.Type).
Annotations(entsql.OnDelete(entsql.Cascade)),
}
}

上述示例配置了外键,使其能够将父表中行数据的删除操作级联到子表中匹配的行数据。

数据库评论

默认情况下,表和列评论不会存储在数据库中。但可通过使用 WithComments(true) 注解启用此功能。例如:

ent/schema/user.go
package schema

import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}

// Annotations of the User.
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
// Adding this annotation to the schema enables
// comments for the table and all its fields.
entsql.WithComments(true),
schema.Comment("Comment that appears in both the schema and the generated code"),
}
}

// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Comment("The user's name"),
field.Int("age").
Comment("The user's age"),
field.String("skipped").
Comment("This comment won't be stored in the database").
// Explicitly disable comments for this field.
Annotations(
entsql.WithComments(false),
),
}
}