跳到主要内容

注解

结构注解(Schema annotations) 允许附加元数据到结构对象(例如字段和边) 上面,并且将元数据注入到外部模板中。 注解是一种Go类型,它能进行JSON序列化(例如 struct, map 或 slice),并且需要实现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类型持有用户实体的结构(schema)定义
type User struct {
ent.Schema
}

// 用户实体的注解
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "Users"},
}
}

// 用户实体的字段
func (User) Fields() []ent.Field {
return []ent.Field{
field.Int("age"),
field.String("name"),
}
}

Custom Table Schema

Using the Atlas migration engine, an Ent schema can be defined and managed across multiple database schemas. Check out the multi-schema doc for more information.

Foreign Keys Configuration

Ent allows to customize the foreign key creation and provide a referential action for the ON DELETE clause:

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类型持有用户实体的结构(schema)定义
type User struct {
ent.Schema
}

// 用户实体的字段
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Default("Unknown"),
}
}

// 用户实体的关系
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("posts", Post.Type).
Annotations(entsql.OnDelete(entsql.Cascade)),
}
}

The example above configures the foreign key to cascade the deletion of rows in the parent table to the matching rows in the child table.

Database Comments

By default, table and column comments are not stored in the database. However, this functionality can be enabled by using the WithComments(true) annotation. For example:

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),
),
}
}