From 0d7ed6f4a189143b99eca3c6669370d87ab8b720 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 26 Mar 2024 11:30:38 +0800 Subject: [PATCH] New Crowdin updates (#747) * New translations models.md (Indonesian) * New translations query.md (Chinese Simplified) * New translations advanced_query.md (Chinese Simplified) * New translations query.md (Portuguese, Brazilian) * New translations query.md (Portuguese, Brazilian) * New translations advanced_query.md (Japanese) * New translations associations.md (Chinese Simplified) * New translations many_to_many.md (Chinese Simplified) * New translations create.md (Chinese Simplified) * New translations context.md (Portuguese, Brazilian) * New translations models.md (Chinese Simplified) * New translations context.md (Portuguese, Brazilian) * New translations context.md (Portuguese, Brazilian) * New translations conventions.md (Portuguese, Brazilian) --- pages/id_ID/docs/models.md | 34 +++++++++++++------------- pages/ja_JP/docs/advanced_query.md | 2 +- pages/pt_BR/docs/context.md | 38 +++++++++++++++--------------- pages/pt_BR/docs/conventions.md | 22 ++++++++--------- pages/pt_BR/docs/query.md | 28 +++++++++++----------- pages/zh_CN/docs/advanced_query.md | 2 +- pages/zh_CN/docs/associations.md | 6 ++--- pages/zh_CN/docs/create.md | 4 +--- pages/zh_CN/docs/many_to_many.md | 2 +- pages/zh_CN/docs/models.md | 8 +++---- pages/zh_CN/docs/query.md | 2 +- 11 files changed, 73 insertions(+), 75 deletions(-) diff --git a/pages/id_ID/docs/models.md b/pages/id_ID/docs/models.md index 4f85c2232b2..60f73b8ad6c 100644 --- a/pages/id_ID/docs/models.md +++ b/pages/id_ID/docs/models.md @@ -9,34 +9,34 @@ GORM simplifies database interactions by mapping Go structs to database tables. Models are defined using normal structs. These structs can contain fields with basic Go types, pointers or aliases of these types, or even custom types, as long as they implement the [Scanner](https://pkg.go.dev/database/sql/?tab=doc#Scanner) and [Valuer](https://pkg.go.dev/database/sql/driver#Valuer) interfaces from the `database/sql` package -Consider the following example of a `User` model: +Pertimbangkan contoh model `User` berikut ini: ```go type User struct { - ID uint // Standard field for the primary key - Name string // A regular string field - Email *string // A pointer to a string, allowing for null values - Age uint8 // An unsigned 8-bit integer - Birthday *time.Time // A pointer to time.Time, can be null - MemberNumber sql.NullString // Uses sql.NullString to handle nullable strings - ActivatedAt sql.NullTime // Uses sql.NullTime for nullable time fields - CreatedAt time.Time // Automatically managed by GORM for creation time - UpdatedAt time.Time // Automatically managed by GORM for update time + ID uint // Bidang standar untuk primary key + Name string // Bidang string biasa + Email *string // Sebuah pointer string, yang memungkinkan nilai null + Age uint8 // Bilangan bulat positif 8-bit + Birthday *time.Time // Sebuah pointer time.Time, bisa berupa nilai null + MemberNumber sql.NullString // Menggunakan sql.NullString untuk menangani string yang bisa bernilai null + ActivatedAt sql.NullTime // Menggunakan sql.NullTime untuk bidang waktu yang bisa bernilai null + CreatedAt time.Time // Dikelola secara otomatis oleh GORM untuk waktu pembuatan + UpdatedAt time.Time // Dikelola secara otomatis oleh GORM untuk waktu pembaruan } ``` -In this model: +Dalam model ini: -- Basic data types like `uint`, `string`, and `uint8` are used directly. -- Pointers to types like `*string` and `*time.Time` indicate nullable fields. -- `sql.NullString` and `sql.NullTime` from the `database/sql` package are used for nullable fields with more control. -- `CreatedAt` and `UpdatedAt` are special fields that GORM automatically populates with the current time when a record is created or updated. +- Tipe data dasar seperti `uint`, `string`, dan `uint8` digunakan secara langsung. +- Sebuah pointer ke tipe seperti `*string` dan `*time.Time` mengindikasikan bidang yang dapat bernilai null. +- `sql.NullString` dan `sql.NullTime` dari package `database/sql` digunakan untuk bidang yang dapat bernilai null dengan kontrol yang lebih luas. +- `CreatedAt` dan `UpdatedAt` adalah bidang khusus yang secara otomatis diisi oleh GORM dengan waktu saat ini ketika record dibuat atau diperbarui. -In addition to the fundamental features of model declaration in GORM, it's important to highlight the support for serialization through the serializer tag. This feature enhances the flexibility of how data is stored and retrieved from the database, especially for fields that require custom serialization logic, See [Serializer](serializer.html) for a detailed explanation +Selain fitur dasar deklarasi model di GORM, penting untuk menyoroti dukungan serialisasi melalui tag serializer. Fitur ini meningkatkan fleksibilitas bagaimana data disimpan dan diambil dari database, terutama untuk bidang yang memerlukan logika serialisasi khusus, Lihat [Serializer](serializer.html) untuk penjelasan yang lebih rinci ### Konvensi -1. **Primary Key**: GORM uses a field named `ID` as the default primary key for each model. +1. **Primary Key**: GORM menggunakan bidang bernama `ID` sebagai primary key default untuk setiap model. 2. **Table Names**: By default, GORM converts struct names to `snake_case` and pluralizes them for table names. For instance, a `User` struct becomes `users` in the database. diff --git a/pages/ja_JP/docs/advanced_query.md b/pages/ja_JP/docs/advanced_query.md index 24ccd06e99e..9ec155f7a61 100644 --- a/pages/ja_JP/docs/advanced_query.md +++ b/pages/ja_JP/docs/advanced_query.md @@ -5,7 +5,7 @@ layout: page ## 便利なフィールドの選択 -In GORM, you can efficiently select specific fields using the [`Select`](query.html) method. This is particularly useful when dealing with large models but requiring only a subset of fields, especially in API responses. +GORMでは、 [`Select`](query.html) メソッドを使用して特定のフィールドを効率的に選択できます。 これは特に、大きなモデルの中の一部のフィールドのみが必要であるような場合(APIレスポンスのような)に便利です。 ```go type User struct { diff --git a/pages/pt_BR/docs/context.md b/pages/pt_BR/docs/context.md index 41ebb709568..7dfe58d38b4 100644 --- a/pages/pt_BR/docs/context.md +++ b/pages/pt_BR/docs/context.md @@ -3,19 +3,19 @@ title: Contexto layout: page --- -GORM's context support, enabled by the `WithContext` method, is a powerful feature that enhances the flexibility and control of database operations in Go applications. It allows for context management across different operational modes, timeout settings, and even integration into hooks/callbacks and middlewares. Let's delve into these various aspects: +Suporte de contexto do GORM, habilitado pelo método `WithContext`, é um recurso poderoso que melhora a flexibilidade e o controle das operações do banco de dados no Go aplicativos. Isto possibilita o gerenciamento de contexto entre diferentes modos operacionais como configuração de timeout, integração entre hooks/callbacks e middlewares. Vamos nos aprofundar nestes diferentes aspectos: ### Modo de sessão única -Single session mode is appropriate for executing individual operations. It ensures that the specific operation is executed within the context's scope, allowing for better control and monitoring. +Modo de sessão única é apropriado para executar operações simples. Isto garante que a operação específica seja executada no escopo do contexto, permitindo melhor controle e monitoramento. ```go db.WithContext(ctx).Find(&users) ``` -### Continuous Session Mode +### Modo sessão continuada -Continuous session mode is ideal for performing a series of related operations. It maintains the context across these operations, which is particularly useful in scenarios like transactions. +O modo sessão continuada é ideal para execução de operações em série. O contexto é mantido entre as operações e é particularmente útil em cenários como transações. ```go tx := db.WithContext(ctx) @@ -23,9 +23,9 @@ tx.First(&user, 1) tx.Model(&user).Update("role", "admin") ``` -### Context Timeout +### Timeout de contexto -Setting a timeout on the context passed to `db.WithContext` can control the duration of long-running queries. This is crucial for maintaining performance and avoiding resource lock-ups in database interactions. +Configurar timeout no contexto e passar para `db.WithContext` para controlar a duração de queries demoradas. Isto é crucial para manter a desempenho e evitar o bloqueio de recursos em iterações com o banco de dados. ```go ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) @@ -34,21 +34,21 @@ defer cancel() db.WithContext(ctx).Find(&users) ``` -### Context in Hooks/Callbacks +### Contexto em Hooks/Callbacks -The context can also be accessed within GORM's hooks/callbacks. This enables contextual information to be used during these lifecycle events. +O contexto também pode ser acessado por hooks/callbacks no GORM. Isto habilita informações contextuais para serem utilizadas durante o ciclo de vida dos eventos. ```go func (u *User) BeforeCreate(tx *gorm.DB) (err error) { ctx := tx.Statement.Context - // ... use context + // ... uso do contexto return } ``` -### Integration with Chi Middleware +### Integração com Chi Middleware -GORM's context support extends to web server middlewares, such as those in the Chi router. This allows setting a context with a timeout for all database operations within the scope of a web request. +O contexto do GORM suporta extensão para middleware de servidores web, como este no roteador do Chi. Assim permitindo a configuração de contexto com timeout para todas as operações de banco de dados no escopo do request. ```go func SetDBMiddleware(next http.Handler) http.Handler { @@ -59,26 +59,26 @@ func SetDBMiddleware(next http.Handler) http.Handler { }) } -// Router setup +// Configuração do roteador r := chi.NewRouter() r.Use(SetDBMiddleware) -// Route handlers +// Configurações de rotas r.Get("/", func(w http.ResponseWriter, r *http.Request) { db, ok := r.Context().Value("DB").(*gorm.DB) - // ... db operations + // ... Operações de BD }) r.Get("/user", func(w http.ResponseWriter, r *http.Request) { db, ok := r.Context().Value("DB").(*gorm.DB) - // ... db operations + // ... Operações de BD }) ``` -**Note**: Setting the `Context` with `WithContext` is goroutine-safe. This ensures that database operations are safely managed across multiple goroutines. For more details, refer to the [Session documentation](session.html) in GORM. +**Nota**: A configuração do `Context` com `WithContext` é goroutine-safe. Isto garante que as operações de bancos de dados são gerenciadas entre múltiplas goroutines. Para mais detalhes, consulte a [documentação de Session](session.html) em GORM. -### Logger Integration +### Integração com Logger -GORM's logger also accepts `Context`, which can be used for log tracking and integrating with existing logging infrastructures. +O GORM logger também aceita `Context`, que pode ser utilizado para log tracking e integração com a infraestrutura de log existente. -Refer to [Logger documentation](logger.html) for more details. +Consulte a [documentação do Logger](logger.html) para mais detalhes. diff --git a/pages/pt_BR/docs/conventions.md b/pages/pt_BR/docs/conventions.md index 8318f7b2e7b..922fe1e3d77 100644 --- a/pages/pt_BR/docs/conventions.md +++ b/pages/pt_BR/docs/conventions.md @@ -3,30 +3,30 @@ title: Convenções layout: page --- -## `ID` as Primary Key +## ID como chave primária -GORM uses the field with the name `ID` as the table's primary key by default. +GORM usa o campo com o nome ID como chave primária por padrão. ```go type User struct { -  ID   string // field named `ID` will be used as a primary field by default -  Name string + ID string // campo `ID` vai ser usado como chave primária por padrão + Name string } ``` -You can set other fields as primary key with tag `primaryKey` +Você pode usar outro campo como chave primária usando a tag primaryKey ```go -// Set field `UUID` as primary field +// Configurando o campo `UUID` como chave primária type Animal struct { -  ID     int64 -  UUID   string `gorm:"primaryKey"` -  Name   string -  Age    int64 + ID int64 + UUID string `gorm:"primaryKey"` + Name string + Age int64 } ``` -Also check out [Composite Primary Key](composite_primary_key.html) +Veja também composição de chave primária ## Pluralized Table Name diff --git a/pages/pt_BR/docs/query.md b/pages/pt_BR/docs/query.md index 2170881275c..83469335d82 100644 --- a/pages/pt_BR/docs/query.md +++ b/pages/pt_BR/docs/query.md @@ -3,20 +3,20 @@ title: Consulta layout: page --- -## Retrieving a single object +## Recuperando um único objeto -GORM provides `First`, `Take`, `Last` methods to retrieve a single object from the database, it adds `LIMIT 1` condition when querying the database, and it will return the error `ErrRecordNotFound` if no record is found. +GORM fornece os métodos `First`, `Take` e `Last` para recuperar um único objeto do banco de dados, adiciona a condição `LIMIT 1` ao consultar o banco de dados e retornará o erro `ErrRecordNotFound` se nenhum registro for encontrado. ```go -// Get the first record ordered by primary key +// Obtém o primeiro registro ordenado pela chave primária db.First(&user) // SELECT * FROM users ORDER BY id LIMIT 1; -// Get one record, no specified order +// Obtém um registro, sem ordem especificada db.Take(&user) // SELECT * FROM users LIMIT 1; -// Get last record, ordered by primary key desc +// Obtém o último registro, ordenado em ordem decrescente pela chave primária db.Last(&user) // SELECT * FROM users ORDER BY id DESC LIMIT 1; @@ -24,42 +24,42 @@ result := db.First(&user) result.RowsAffected // returns count of records found result.Error // returns error or nil -// check error ErrRecordNotFound +// Verifica o erro ErrRecordNotFound errors.Is(result.Error, gorm.ErrRecordNotFound) ``` {% note warn %} -If you want to avoid the `ErrRecordNotFound` error, you could use `Find` like `db.Limit(1).Find(&user)`, the `Find` method accepts both struct and slice data +Se você quer evitar o erro `ErrRecordNotFound`, você pode usar `Find` como `db.Limit(1).Find(&user)`, o método `Find` aceita dados de struct e slice {% endnote %} {% note warn %} -Using `Find` without a limit for single object `db.Find(&user)` will query the full table and return only the first object which is not performant and nondeterministic +Usando `Find` sem um limite para um único objeto `db.Find(&user)` consultará a tabela completa e retornará apenas o primeiro objeto no qual não é performático e não é determinístico {% endnote %} -The `First` and `Last` methods will find the first and last record (respectively) as ordered by primary key. They only work when a pointer to the destination struct is passed to the methods as argument or when the model is specified using `db.Model()`. Additionally, if no primary key is defined for relevant model, then the model will be ordered by the first field. For example: +Os métodos `First` e `Last` encontrarão o primeiro e último registro (respectivamente), ordenado pela chave primária. Eles só funcionam quando um ponteiro para a struct de destino é passado para os métodos como argumento ou quando o modelo é especificado usando `db.Model()`. Além disso, se nenhuma chave primária for definida para modelo relevante, então o modelo será ordenado pelo primeiro campo. Por exemplo: ```go var user User var users []User -// works because destination struct is passed in +// funciona porque a struct de destino é passada db.First(&user) // SELECT * FROM `users` ORDER BY `users`.`id` LIMIT 1 -// works because model is specified using `db.Model()` +// funciona porque o modelo é especificado usando `db.Model()` result := map[string]interface{}{} db.Model(&User{}).First(&result) // SELECT * FROM `users` ORDER BY `users`.`id` LIMIT 1 -// doesn't work +// não funciona result := map[string]interface{}{} db.Table("users").First(&result) -// works with Take +// funciona com `Take` result := map[string]interface{}{} db.Table("users").Take(&result) -// no primary key defined, results will be ordered by first field (i.e., `Code`) +// nenhuma chave primária definida, os resultados serão ordenados pelo primeiro campo (ou seja, `Code`) type Language struct { Code string Name string diff --git a/pages/zh_CN/docs/advanced_query.md b/pages/zh_CN/docs/advanced_query.md index 2bf63e1cf87..37256b243e8 100644 --- a/pages/zh_CN/docs/advanced_query.md +++ b/pages/zh_CN/docs/advanced_query.md @@ -172,7 +172,7 @@ db.Table("users").Find(&results) ## FirstOrInit -GORM 的 `First OrInit` 方法用于获取与特定条件匹配的第一条记录,如果没有成功获取,就初始化一个新实例。 这个方法与结构和map条件兼容,并且在使用 `Attrs` 和 `Assign` 方法时有着更多的灵活性。 +GORM 的 `FirstOrInit` 方法用于获取与特定条件匹配的第一条记录,如果没有成功获取,就初始化一个新实例。 这个方法与结构和map条件兼容,并且在使用 `Attrs` 和 `Assign` 方法时有着更多的灵活性。 ```go // 如果没找到 name 为 "non_existing" 的 User,就初始化一个新的 User diff --git a/pages/zh_CN/docs/associations.md b/pages/zh_CN/docs/associations.md index e8c80b1f9e7..95ec067c028 100644 --- a/pages/zh_CN/docs/associations.md +++ b/pages/zh_CN/docs/associations.md @@ -26,7 +26,7 @@ user := User{ }, } -// Creating a user along with its associated addresses, emails, and languages +// 创建用户及其关联的地址、电子邮件和语言 db.Create(&user) // BEGIN TRANSACTION; // INSERT INTO "addresses" (address1) VALUES ("Billing Address - Address 1"), ("Shipping Address - Address 1") ON DUPLICATE KEY DO NOTHING; @@ -44,9 +44,9 @@ db.Save(&user) 对于需要全面更新关联数据(不止外键)的情况,就应该使用 `FullSaveAssociations` 方法。 ```go -// Update a user and fully update all its associations +// 更新用户并完全更新其所有关联 db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user) -// SQL: Fully updates addresses, users, emails tables, including existing associated records +// SQL:完全更新地址、用户、电子邮件表,包括现有的关联记录 ``` 使用`FullSaveAssociations` 方法来确保模型的整体状态,包括其所有关联都反映在了数据库中,从在应用中保持数据的完整性和一致性。 diff --git a/pages/zh_CN/docs/create.md b/pages/zh_CN/docs/create.md index c0236d7e410..e45beacbff4 100644 --- a/pages/zh_CN/docs/create.md +++ b/pages/zh_CN/docs/create.md @@ -25,10 +25,8 @@ users := []*User{ result := db.Create(users) // 传递切片以插入多行数据 result.Error // 返回 error -result.RowsAffected // 返回插入记录的条数 +result.RowsAffected // 返回插入记录的条数 ``` - -{% note warn %} **NOTE** 你无法向 'create' 传递结构体,所以你应该传入数据的指针. {% endnote %} diff --git a/pages/zh_CN/docs/many_to_many.md b/pages/zh_CN/docs/many_to_many.md index 877f4ea11cf..070804af2c4 100644 --- a/pages/zh_CN/docs/many_to_many.md +++ b/pages/zh_CN/docs/many_to_many.md @@ -127,7 +127,7 @@ GORM 可以通过 `Preload` 预加载 has many 关联的记录,查看 [预加 ## 自定义连接表 -`JoinTable` can be a full-featured model, like having `Soft Delete`,`Hooks` supports and more fields, you can set it up with `SetupJoinTable`, for example: +`连接表` 可以是一个功能齐全的模型,比如支持 `软删除`、`钩子函数`功能,并且可以具有更多字段。您可以通过 `SetupJoinTable` 设置,例如: {% note warn %} **注意:** 自定义连接表要求外键是复合主键或复合唯一索引 diff --git a/pages/zh_CN/docs/models.md b/pages/zh_CN/docs/models.md index 21ef55ceb50..13b94d9e111 100644 --- a/pages/zh_CN/docs/models.md +++ b/pages/zh_CN/docs/models.md @@ -3,13 +3,13 @@ title: 模型定义 layout: page --- -GORM simplifies database interactions by mapping Go structs to database tables. Understanding how to declare models in GORM is fundamental for leveraging its full capabilities. +GORM 通过将 Go 结构体(Go structs) 映射到数据库表来简化数据库交互。 了解如何在GORM中定义模型,是充分利用GORM全部功能的基础。 ## 模型定义 -Models are defined using normal structs. These structs can contain fields with basic Go types, pointers or aliases of these types, or even custom types, as long as they implement the [Scanner](https://pkg.go.dev/database/sql/?tab=doc#Scanner) and [Valuer](https://pkg.go.dev/database/sql/driver#Valuer) interfaces from the `database/sql` package +模型是使用普通结构体定义的。 这些结构体可以包含具有基本Go类型、指针或这些类型的别名,甚至是自定义类型(只需要实现 `database/sql` 包中的[Scanner](https://pkg.go.dev/database/sql/?tab=doc#Scanner)和[Valuer](https://pkg.go.dev/database/sql/driver#Valuer)接口)。 -Consider the following example of a `User` model: +考虑以下 `user` 模型的示例: ```go type User struct { @@ -25,7 +25,7 @@ type User struct { } ``` -In this model: +在此模型中: - Basic data types like `uint`, `string`, and `uint8` are used directly. - Pointers to types like `*string` and `*time.Time` indicate nullable fields. diff --git a/pages/zh_CN/docs/query.md b/pages/zh_CN/docs/query.md index 8a4bf2b49b5..c3a6344cbcf 100644 --- a/pages/zh_CN/docs/query.md +++ b/pages/zh_CN/docs/query.md @@ -33,7 +33,7 @@ errors.Is(result.Error, gorm.ErrRecordNotFound) {% endnote %} {% note warn %} -对单个对象使用`Find`而不带limit,`db.Find(&user)`将会查询整个表并且只返回第一个对象,这是性能不高并且不确定的。 +对单个对象使用`Find`而不带limit,`db.Find(&user)`将会查询整个表并且只返回第一个对象,只是性能不高并且不确定的。 {% endnote %} `First` and `Last` 方法会按主键排序找到第一条记录和最后一条记录 (分别)。 只有在目标 struct 是指针或者通过 `db.Model()` 指定 model 时,该方法才有效。 此外,如果相关 model 没有定义主键,那么将按 model 的第一个字段进行排序。 例如: