メインコンテンツへスキップする

アノテーション

スキーマアノテーションは、フィールドやエッジなどのスキーマオブジェクトにメタデータを付加し、それを外部テンプレートに注入することができます。 アノテーションは、JSON raw の値にシリアライズ可能なGoの型(struct,map,sliceなど)で、Annotation インターフェイスを実装している必要があります。

Ent内蔵のアノテーションにより、さまざまなストレージドライバー(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型は、Userエンティティのスキーマ定義を保持しています。
type User struct {
ent.Schema
}

// User型のアノテーション
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Annotation{Table: "Users"},
}
}

// Userのフィールド
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型は、Userエンティティのスキーマ定義を保持しています。
type User struct {
ent.Schema
}

// Userのフィールド
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),
),
}
}