Saltar al contenido principal

Anotaciones

[Traducción Beta No Oficial]

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Las anotaciones de esquema permiten adjuntar metadatos a objetos del esquema como campos y aristas, e inyectarlos en plantillas externas. Una anotación debe ser un tipo de Go serializable a valor JSON raw (por ejemplo, struct, map o slice) e implementar la interfaz Annotation.

Las anotaciones incorporadas permiten configurar los diferentes controladores de almacenamiento (como SQL) y controlar la salida de la generación de código.

Nombre personalizado de tabla

Se puede proporcionar un nombre de tabla personalizado para los tipos usando la anotación entsql de la siguiente manera:

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

Esquema de tabla personalizado

Usando el motor de migraciones Atlas, un esquema de Ent puede definirse y gestionarse en múltiples esquemas de base de datos. Consulta el documento sobre múltiples esquemas para más información.

Configuración de claves foráneas

Ent permite personalizar la creación de claves foráneas y proporcionar una acción referencial para la cláusula 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)),
}
}

El ejemplo anterior configura la clave foránea para propagar en cascada la eliminación de filas en la tabla padre a las filas correspondientes en la tabla hija.

Comentarios en la base de datos

Por defecto, los comentarios de tabla y columna no se almacenan en la base de datos. Sin embargo, esta funcionalidad puede habilitarse usando la anotación WithComments(true). Por ejemplo:

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