diff --git a/pages/ar_SA/community.md b/pages/ar_SA/community.md index f5af60c1032..c1870d5b190 100644 --- a/pages/ar_SA/community.md +++ b/pages/ar_SA/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Contribute to this page diff --git a/pages/ar_SA/docs/create.md b/pages/ar_SA/docs/create.md index 13677bb8a8e..fe1c6c09480 100644 --- a/pages/ar_SA/docs/create.md +++ b/pages/ar_SA/docs/create.md @@ -23,6 +23,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/ar_SA/docs/dbresolver.md b/pages/ar_SA/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/ar_SA/docs/dbresolver.md +++ b/pages/ar_SA/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/ar_SA/docs/migration.md b/pages/ar_SA/docs/migration.md index 0600a6ddfe1..b330c334e9e 100644 --- a/pages/ar_SA/docs/migration.md +++ b/pages/ar_SA/docs/migration.md @@ -264,9 +264,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/ar_SA/gen/database_to_structs.md b/pages/ar_SA/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/ar_SA/gen/database_to_structs.md +++ b/pages/ar_SA/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/ar_SA/gen/query.md b/pages/ar_SA/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/ar_SA/gen/query.md +++ b/pages/ar_SA/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/ar_SA/gen/rawsql_driver.html b/pages/ar_SA/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/ar_SA/gen/rawsql_driver.html +++ b/pages/ar_SA/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/ar_SA/rawsql.html b/pages/ar_SA/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/ar_SA/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/ar_SA/rawsql_driver.html b/pages/ar_SA/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/ar_SA/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/az_AZ/community.md b/pages/az_AZ/community.md index f5af60c1032..c1870d5b190 100644 --- a/pages/az_AZ/community.md +++ b/pages/az_AZ/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Contribute to this page diff --git a/pages/az_AZ/docs/create.md b/pages/az_AZ/docs/create.md index a8bd7a8fdf4..ce5544182c5 100644 --- a/pages/az_AZ/docs/create.md +++ b/pages/az_AZ/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/az_AZ/docs/dbresolver.md b/pages/az_AZ/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/az_AZ/docs/dbresolver.md +++ b/pages/az_AZ/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/az_AZ/docs/migration.md b/pages/az_AZ/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/az_AZ/docs/migration.md +++ b/pages/az_AZ/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/az_AZ/gen/database_to_structs.md b/pages/az_AZ/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/az_AZ/gen/database_to_structs.md +++ b/pages/az_AZ/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/az_AZ/gen/query.md b/pages/az_AZ/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/az_AZ/gen/query.md +++ b/pages/az_AZ/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/az_AZ/gen/rawsql_driver.html b/pages/az_AZ/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/az_AZ/gen/rawsql_driver.html +++ b/pages/az_AZ/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/az_AZ/rawsql.html b/pages/az_AZ/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/az_AZ/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/az_AZ/rawsql_driver.html b/pages/az_AZ/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/az_AZ/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/de_DE/community.md b/pages/de_DE/community.md index 27f517db25e..1bef7a83f4e 100644 --- a/pages/de_DE/community.md +++ b/pages/de_DE/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Trage zu dieser Seite bei diff --git a/pages/de_DE/docs/create.md b/pages/de_DE/docs/create.md index 305d9a07d53..f3b59406d10 100644 --- a/pages/de_DE/docs/create.md +++ b/pages/de_DE/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/de_DE/docs/dbresolver.md b/pages/de_DE/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/de_DE/docs/dbresolver.md +++ b/pages/de_DE/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/de_DE/docs/migration.md b/pages/de_DE/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/de_DE/docs/migration.md +++ b/pages/de_DE/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/de_DE/gen/database_to_structs.md b/pages/de_DE/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/de_DE/gen/database_to_structs.md +++ b/pages/de_DE/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/de_DE/gen/query.md b/pages/de_DE/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/de_DE/gen/query.md +++ b/pages/de_DE/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/de_DE/gen/rawsql_driver.html b/pages/de_DE/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/de_DE/gen/rawsql_driver.html +++ b/pages/de_DE/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/de_DE/rawsql.html b/pages/de_DE/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/de_DE/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/de_DE/rawsql_driver.html b/pages/de_DE/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/de_DE/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/es_ES/community.md b/pages/es_ES/community.md index c0b52d566f2..c674bbb5d4b 100644 --- a/pages/es_ES/community.md +++ b/pages/es_ES/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Filtrado de mapas anidados](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Contribuye a esta página diff --git a/pages/es_ES/docs/create.md b/pages/es_ES/docs/create.md index a0806f8a54e..c9722a76c2d 100644 --- a/pages/es_ES/docs/create.md +++ b/pages/es_ES/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/es_ES/docs/dbresolver.md b/pages/es_ES/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/es_ES/docs/dbresolver.md +++ b/pages/es_ES/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/es_ES/docs/migration.md b/pages/es_ES/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/es_ES/docs/migration.md +++ b/pages/es_ES/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/es_ES/gen/database_to_structs.md b/pages/es_ES/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/es_ES/gen/database_to_structs.md +++ b/pages/es_ES/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/es_ES/gen/query.md b/pages/es_ES/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/es_ES/gen/query.md +++ b/pages/es_ES/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/es_ES/gen/rawsql_driver.html b/pages/es_ES/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/es_ES/gen/rawsql_driver.html +++ b/pages/es_ES/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/es_ES/rawsql.html b/pages/es_ES/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/es_ES/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/es_ES/rawsql_driver.html b/pages/es_ES/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/es_ES/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/fa_IR/community.md b/pages/fa_IR/community.md index 1784ecb1f00..5800a9a5f77 100644 --- a/pages/fa_IR/community.md +++ b/pages/fa_IR/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## مشارکت در بهبود این صفحه diff --git a/pages/fa_IR/docs/create.md b/pages/fa_IR/docs/create.md index a8bd7a8fdf4..ce5544182c5 100644 --- a/pages/fa_IR/docs/create.md +++ b/pages/fa_IR/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/fa_IR/docs/dbresolver.md b/pages/fa_IR/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/fa_IR/docs/dbresolver.md +++ b/pages/fa_IR/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/fa_IR/docs/migration.md b/pages/fa_IR/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/fa_IR/docs/migration.md +++ b/pages/fa_IR/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/fa_IR/gen/database_to_structs.md b/pages/fa_IR/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/fa_IR/gen/database_to_structs.md +++ b/pages/fa_IR/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/fa_IR/gen/query.md b/pages/fa_IR/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/fa_IR/gen/query.md +++ b/pages/fa_IR/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/fa_IR/gen/rawsql_driver.html b/pages/fa_IR/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/fa_IR/gen/rawsql_driver.html +++ b/pages/fa_IR/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/fa_IR/rawsql.html b/pages/fa_IR/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/fa_IR/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/fa_IR/rawsql_driver.html b/pages/fa_IR/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/fa_IR/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/fr_FR/community.md b/pages/fr_FR/community.md index f8eddafc7c5..5b5eda8daeb 100644 --- a/pages/fr_FR/community.md +++ b/pages/fr_FR/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Contribute to this page diff --git a/pages/fr_FR/contribute.md b/pages/fr_FR/contribute.md index 92f9ddb8d7d..bee7fae0fcd 100644 --- a/pages/fr_FR/contribute.md +++ b/pages/fr_FR/contribute.md @@ -1,37 +1,37 @@ --- -title: Contribute to GORM +title: Contribuer à GORM layout: page --- -**You can help to deliver a better GORM! there are many things that you can do:** +**Vous pouvez aider à offrir un meilleur GORM ! il y a beaucoup de choses que vous pouvez faire:** -## Help others to know GORM +## Aider les autres à connaître GORM -* Share GORM with the world by social channels, or simply tell people who might be interested -* Help newcomers to solve questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/go-gorm), [Github Issues](https://github.com/go-gorm/gorm/issues) and [Chat Rooms](/community.html#Chat) -* Write tutorials, record videos, etc... (Don't forget to add them to [the list](/community.html)) -* Help to promote GORM on GitHub by [Starring](https://github.com/go-gorm/gorm/stargazers) and [Watching](https://github.com/go-gorm/gorm/watchers) the [GORM repository](https://github.com/go-gorm/gorm) +* Partagez GORM avec le monde par des canaux sociaux, ou dites simplement aux gens qui pourraient être intéressés +* Aidez les nouveaux arrivants à résoudre les questions sur [Stack Overflow](https://stackoverflow.com/questions/tagged/go-gorm), [Github Issues](https://github.com/go-gorm/gorm/issues) et [Chat Rooms](/community.html#Chat) +* Écrivez des tutoriels, enregistrez des vidéos, etc... (N'oubliez pas de les ajouter à [la liste](/community.html)) +* Aidez à promouvoir GORM sur GitHub par [Starring](https://github.com/go-gorm/gorm/stargazers) et [Regarder](https://github.com/go-gorm/gorm/watchers) le dépôt [GORM](https://github.com/go-gorm/gorm) -## Documentation and Writing +## Documentation et écriture -* Make GORM's documentation better by writing new content, correcting existing material [https://github.com/go-gorm/gorm.io](https://github.com/go-gorm/gorm.io) +* Améliorez la documentation de GORM en écrivant un nouveau contenu, en corrigeant le matériel existant [https://github.com/go-gorm/gorm.io](https://github.com/go-gorm/gorm.io) ### Traduire ce site -You can translate the current site with [https://translate.gorm.io](https://translate.gorm.io) +Vous pouvez traduire le site actuel avec [https://translate.gorm.io](https://translate.gorm.io) -To translate GORM in your language you need to post a request in the [Github issues](https://github.com/go-gorm/gorm.io/issues) for it be added to [https://translate.gorm.io](https://translate.gorm.io). +Pour traduire GORM dans votre langue, vous devez publier une requête dans les [Github issues](https://github.com/go-gorm/gorm.io/issues) pour qu'elle soit ajoutée à [https://translate. orm.io](https://translate.gorm.io). -## Program +## Programme -* Create a pull request on [Github](https://github.com/go-gorm/gorm) to fix issues, new features -* Create open-source plugins for GORM (Don't forget to add them to [the list](/community.html#Open-Sources)) +* Créez une pull request sur [Github](https://github.com/go-gorm/gorm) pour résoudre les problèmes, de nouvelles fonctionnalités +* Créer des plugins open-source pour GORM (N'oubliez pas de les ajouter à [la liste](/community.html#Open-Sources)) -## Donations +## Dons -Your kindness and generosity is greatly appreciated, many thanks to all our sponsors! +Votre gentillesse et votre générosité sont grandement appréciées, merci à tous nos sponsors! -* Github Sponsors (Platinum, Gold Sponsors etc) +* Sponsors Github (Platinum, Sponsors Or etc) [https://github.com/sponsors/jinzhu](https://github.com/sponsors/jinzhu) diff --git a/pages/fr_FR/docs/associations.md b/pages/fr_FR/docs/associations.md index 42e5a8e6131..f3044e30115 100644 --- a/pages/fr_FR/docs/associations.md +++ b/pages/fr_FR/docs/associations.md @@ -5,7 +5,7 @@ layout: page ## Auto Create/Update -GORM will auto-save associations and its reference using [Upsert](create.html#upsert) when creating/updating a record. +GORM enregistrera automatiquement les associations et ses références en utilisant [Upsert](create.html#upsert) lors de la création/mise à jour d'un enregistrement. ```go user := User{ @@ -34,7 +34,7 @@ db.Create(&user) db.Save(&user) ``` -If you want to update associations's data, you should use the `FullSaveAssociations` mode: +Si vous voulez mettre à jour les données des associations, vous devez utiliser le mode `FullSaveAssociations`: ```go db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user) @@ -47,7 +47,7 @@ db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user) ## Skip Auto Create/Update -To skip the auto save when creating/updating, you can use `Select` or `Omit`, for example: +Pour ignorer la sauvegarde automatique lors de la création/mise à jour, vous pouvez utiliser ` Select ` ou `Omit`, par exemple : ```go user := User{ @@ -75,20 +75,20 @@ db.Omit(clause.Associations).Create(&user) ``` {% note warn %} -**NOTE:** For many2many associations, GORM will upsert the associations before creating the join table references, if you want to skip the upserting of associations, you could skip it like: +**NOTE :** Pour de nombreuses associations, GORM fera la mise en valeur des associations avant de créer les références de la table d'association, si vous voulez sauter l'insertion des associations, vous pouvez passer comme : ```go db.Omit("Languages.*").Create(&user) ``` -The following code will skip the creation of the association and its references +Le code suivant ignorera la création de l'association et de ses références ```go db.Omit("Languages").Create(&user) ``` {% endnote %} -## Select/Omit Association fields +## Select/Omit Champs d'association ```go user := User{ @@ -104,9 +104,9 @@ db.Select("BillingAddress.Address1", "BillingAddress.Address2").Create(&user) db.Omit("BillingAddress.Address2", "BillingAddress.CreatedAt").Create(&user) ``` -## Association Mode +## Mode d'association -Association Mode contains some commonly used helper methods to handle relationships +Le mode association contient des méthodes d'aide couramment utilisées pour gérer les relations ```go // Start Association Mode @@ -118,15 +118,15 @@ db.Model(&user).Association("Languages") db.Model(&user).Association("Languages").Error ``` -### Find Associations +### Trouver des associations -Find matched associations +Trouver les associations correspondantes ```go db.Model(&user).Association("Languages").Find(&languages) ``` -Find associations with conditions +Trouver des associations avec des conditions ```go codes := []string{"zh-CN", "en-US", "ja-JP"} @@ -135,9 +135,9 @@ db.Model(&user).Where("code IN ?", codes).Association("Languages").Find(&languag db.Model(&user).Where("code IN ?", codes).Order("code desc").Association("Languages").Find(&languages) ``` -### Append Associations +### Ajouter des associations -Append new associations for `many to many`, `has many`, replace current association for `has one`, `belongs to` +Ajouter de nouvelles associations pour `many to many`, `has many`, remplacer l'association actuelle pour `has one`, `belongs to` ```go db.Model(&user).Association("Languages").Append([]Language{languageZH, languageEN}) @@ -147,9 +147,9 @@ db.Model(&user).Association("Languages").Append(&Language{Name: "DE"}) db.Model(&user).Association("CreditCard").Append(&CreditCard{Number: "411111111111"}) ``` -### Replace Associations +### Remplacer des associations -Replace current associations with new ones +Remplacer les associations actuelles par de nouvelles associations ```go db.Model(&user).Association("Languages").Replace([]Language{languageZH, languageEN}) @@ -157,9 +157,9 @@ db.Model(&user).Association("Languages").Replace([]Language{languageZH, language db.Model(&user).Association("Languages").Replace(Language{Name: "DE"}, languageEN) ``` -### Delete Associations +### Supprimer des associations -Remove the relationship between source & arguments if exists, only delete the reference, won't delete those objects from DB. +Supprimer la relation entre les arguments source & s'il existe, supprimer seulement la référence, ne supprimera pas ces objets de la base de données. ```go db.Model(&user).Association("Languages").Delete([]Language{languageZH, languageEN}) @@ -168,15 +168,15 @@ db.Model(&user).Association("Languages").Delete(languageZH, languageEN) ### Clear Associations -Remove all reference between source & association, won't delete those associations +Supprimer toutes les références entre l'association source & ne supprimera pas ces associations ```go db.Model(&user).Association("Languages").Clear() ``` -### Count Associations +### Nombre d'associations -Return the count of current associations +Renvoie le nombre d'associations actuelles ```go db.Model(&user).Association("Languages").Count() @@ -188,7 +188,7 @@ db.Model(&user).Where("code IN ?", codes).Association("Languages").Count() ### Batch Data -Association Mode supports batch data, e.g: +Le mode association supporte les données par lot, par exemple: ```go // Find all roles for all users @@ -208,11 +208,11 @@ db.Model(&users).Association("Team").Append(&userA, &userB, &[]User{userA, userB db.Model(&users).Association("Team").Replace(&userA, &userB, &[]User{userA, userB, userC}) ``` -## Delete Association Record +## Supprimer l'enregistrement de l'association -By default, `Replace`/`Delete`/`Clear` in `gorm.Association` only delete the reference, that is, set old associations's foreign key to null. +Par défaut `Replace`/`Delete`/`Clear` dans `gorm.Association` ne supprime que la référence, qui est, définit la clé étrangère des anciennes associations à null. -You can delete those objects with `Unscoped` (it has nothing to do with `ManyToMany`). +Vous pouvez supprimer ces objets avec `Unscoped` (cela n'a rien à voir avec `ManyToMany`). How to delete is decided by `gorm.DB`. diff --git a/pages/fr_FR/docs/belongs_to.md b/pages/fr_FR/docs/belongs_to.md index f4f2bf81b3a..449d4b56e57 100644 --- a/pages/fr_FR/docs/belongs_to.md +++ b/pages/fr_FR/docs/belongs_to.md @@ -1,68 +1,68 @@ --- -title: Belongs To +title: Appartient à (Belongs To) layout: page --- -## Belongs To +## Appartient à (Belongs To) -A `belongs to` association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. +Une association `belongs to` met en place une connexion individuelle avec un autre modèle, de telle sorte que chaque instance du modèle déclarant "appartient" à une instance de l'autre modèle. -For example, if your application includes users and companies, and each user can be assigned to exactly one company, the following types represent that relationship. Notice here that, on the `User` object, there is both a `CompanyID` as well as a `Company`. By default, the `CompanyID` is implicitly used to create a foreign key relationship between the `User` and `Company` tables, and thus must be included in the `User` struct in order to fill the `Company` inner struct. +Par exemple, si votre application comprend des utilisateurs et des entreprises, et que chaque utilisateur peut être assigné à une seule entreprise, les types suivants représentent cette relation. Notez ici que, sur l'objet `User` , il y a à la fois une `CompanyID` ainsi qu'une `Company`. Par défaut, la `CompanyID` est implicitement utilisée pour créer une relation clé étrangère entre les tables `User` et `Company` et donc doit être inclus dans la structure `User` afin de remplir la structure intérieure `Company`. ```go -// `User` belongs to `Company`, `CompanyID` is the foreign key +// `User` appartient à `Company`, `CompanyID` est la clé étrangère type User struct { gorm.Model - Name string + Name string CompanyID int - Company Company + Company } type Company struct { - ID int + ID int Name string } ``` -Refer to [Eager Loading](belongs_to.html#Eager-Loading) for details on populating the inner struct. +Reportez-vous à [Eager Loading](belongs_to.html#Eager-Loading) pour plus de détails sur le remplissage de la structure intérieure. -## Override Foreign Key +## Redéfinir la clé étrangère -To define a belongs to relationship, the foreign key must exist, the default foreign key uses the owner's type name plus its primary field name. +Pour définir une relation d'appartenance, la clé étrangère doit exister, la clé étrangère par défaut utilise le nom de type du propriétaire plus son nom de champ primaire. -For the above example, to define the `User` model that belongs to `Company`, the foreign key should be `CompanyID` by convention +Pour l'exemple ci-dessus, définir le modèle `User` qui appartient à `Company`, la clé étrangère doit être `CompanyID` par convention -GORM provides a way to customize the foreign key, for example: +GORM fournit un moyen de personnaliser la clé étrangère, par exemple : ```go type User struct { gorm.Model - Name string + Name string CompanyRefer int - Company Company `gorm:"foreignKey:CompanyRefer"` - // use CompanyRefer as foreign key + Company `gorm:"foreignKey:CompanyRefer"` + // utiliser CompanyRefer comme clé étrangère } type Company struct { - ID int + ID int Name string } ``` -## Override References +## Surcharger les références -For a belongs to relationship, GORM usually uses the owner's primary field as the foreign key's value, for the above example, it is `Company`'s field `ID`. +Pour une appartenance à une relation, GORM utilise généralement le champ principal du propriétaire comme valeur de la clé étrangère, pour l'exemple ci-dessus, il s'agit du champ `Company`du champ `ID`. -When you assign a user to a company, GORM will save the company's `ID` into the user's `CompanyID` field. +Lorsque vous assignez un utilisateur à une entreprise, GORM enregistrera l' `ID` de l'entreprise dans le champ `CompanyID` de l'utilisateur. -You are able to change it with tag `references`, e.g: +Vous pouvez le modifier avec le tag `references`, par exemple: ```go type User struct { gorm.Model Name string CompanyID string - Company Company `gorm:"references:Code"` // use Code as references + Company Company `gorm:"references:Code"` // utilise Code comme references } type Company struct { @@ -73,7 +73,7 @@ type Company struct { ``` {% note warn %} -**NOTE** GORM usually guess the relationship as `has one` if override foreign key name already exists in owner's type, we need to specify `references` in the `belongs to` relationship. +**NOTE** GORM devine généralement la relation comme `has one` si le nom de la clé étrangère est déjà remplacé dans le type du propriétaire, nous devons spécifier `references` dans la relation `belongs to`. {% endnote %} ```go @@ -81,7 +81,7 @@ type User struct { gorm.Model Name string CompanyID string - Company Company `gorm:"references:CompanyID"` // use Company.CompanyID as references + Company Company `gorm:"references:CompanyID"` // utilise Company.CompanyID comme references } type Company struct { @@ -91,17 +91,17 @@ type Company struct { } ``` -## CRUD with Belongs To +## CRUD avec Belongs To -Please checkout [Association Mode](associations.html#Association-Mode) for working with belongs to relations +Veuillez consulter le [Mode d'association](associations.html#Association-Mode) pour travailler avec les relations belongs to -## Eager Loading +## Chargement Eager (pressé) -GORM allows eager loading belongs to associations with `Preload` or `Joins`, refer [Preloading (Eager loading)](preload.html) for details +GORM permet au chargement désireux d'appartenir à des associations avec `Preload` ou `Joins`, se référer à [Préchargement (Eager loading)](preload.html) pour plus de détails -## FOREIGN KEY Constraints +## Contraintes de la CLÉ étrangère -You can setup `OnUpdate`, `OnDelete` constraints with tag `constraint`, it will be created when migrating with GORM, for example: +Vous pouvez configurer les contraintes `OnUpdate`, `OnDelete` avec la contrainte de balise `constraint`, il sera créé lors de la migration avec GORM, par exemple : ```go type User struct { diff --git a/pages/fr_FR/docs/composite_primary_key.md b/pages/fr_FR/docs/composite_primary_key.md index f538854c18a..8da3d59606f 100644 --- a/pages/fr_FR/docs/composite_primary_key.md +++ b/pages/fr_FR/docs/composite_primary_key.md @@ -1,20 +1,20 @@ --- -title: Composite Primary Key +title: Clé primaire composite layout: page --- -Set multiple fields as primary key creates composite primary key, for example: +Définir plusieurs champs comme clé primaire crée une clé primaire composite, par exemple : ```go type Product struct { - ID string `gorm:"primaryKey"` + ID string `gorm:"primaryKey"` LanguageCode string `gorm:"primaryKey"` - Code string - Name string + Code string + Name string } ``` -**Note** integer `PrioritizedPrimaryField` enables `AutoIncrement` by default, to disable it, you need to turn off `autoIncrement` for the int fields: +**Note**integer `PrioritizedPrimaryField` active `Auto-Increment` par défaut, pour le désactiver, vous devez désactiver `autoIncrement` pour les champs int : ```go type Product struct { diff --git a/pages/fr_FR/docs/connecting_to_the_database.md b/pages/fr_FR/docs/connecting_to_the_database.md index 8deb225b1f6..7d74c70bf08 100644 --- a/pages/fr_FR/docs/connecting_to_the_database.md +++ b/pages/fr_FR/docs/connecting_to_the_database.md @@ -1,9 +1,9 @@ --- -title: Connecting to a Database +title: Connexion à la base de données layout: page --- -GORM officially supports the databases MySQL, PostgreSQL, SQLite, SQL Server, and TiDB +GORM supporte officiellement les bases de données MySQL, PostgreSQL, SQLite, SQL Server et TiDB ## MySQL @@ -21,10 +21,10 @@ func main() { ``` {% note warn %} -**NOTE:** To handle `time.Time` correctly, you need to include `parseTime` as a parameter. ([more parameters](https://github.com/go-sql-driver/mysql#parameters)) To fully support UTF-8 encoding, you need to change `charset=utf8` to `charset=utf8mb4`. See [this article](https://mathiasbynens.be/notes/mysql-utf8mb4) for a detailed explanation +**NOTE :** Pour gérer `time.Time` correctement, vous devez inclure `parseTime` comme paramètre. ([plus de paramètres](https://github.com/go-sql-driver/mysql#parameters)) Pour supporter pleinement l'encodage UTF-8, vous devez changer `charset=utf8` à `charset=utf8mb4`. Voir [cet article](https://mathiasbynens.be/notes/mysql-utf8mb4) pour une explication détaillée {% endnote %} -MySQL Driver provides a [few advanced configurations](https://github.com/go-gorm/mysql) which can be used during initialization, for example: +MySQL Driver fournit [quelques configurations avancées ](https://github.com/go-gorm/mysql) qui peut être utilisé lors d'initialisation, for exemple : ```go db, err := gorm.Open(mysql.New(mysql.Config{ @@ -37,9 +37,9 @@ db, err := gorm.Open(mysql.New(mysql.Config{ }), &gorm.Config{}) ``` -### Customize Driver +### Personnaliser le Driver -GORM allows to customize the MySQL driver with the `DriverName` option, for example: +GORM permet de personnaliser le Driver MySQL avec l'option `DriverName` par exemple : ```go import ( diff --git a/pages/fr_FR/docs/constraints.md b/pages/fr_FR/docs/constraints.md index 8a9e37219e6..cf24dd79739 100644 --- a/pages/fr_FR/docs/constraints.md +++ b/pages/fr_FR/docs/constraints.md @@ -1,13 +1,13 @@ --- -title: Constraints +title: Contraintes layout: page --- -GORM allows create database constraints with tag, constraints will be created when [AutoMigrate or CreateTable with GORM](migration.html) +GORM permet de créer de base de données avec des contraintes, les contraintes sont créées quand [AutoMigrate ou CreateTable avec GORM](migration.html) -## CHECK Constraint +## Contrainte CHECK -Create CHECK constraints with tag `check` +Créer les contraintes CHECK avec le tag `check` ```go type UserIndex struct { @@ -17,13 +17,13 @@ type UserIndex struct { } ``` -## Index Constraint +## Contrainte Index Checkout [Database Indexes](indexes.html) -## Foreign Key Constraint +## Contrainte clé étrangère -GORM will creates foreign keys constraints for associations, you can disable this feature during initialization: +GORM crée des contraintes sur la clé étrangère pour les associations, vous pouvez désactiver cette fonctionnalité lors d'initialisation : ```go db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ @@ -31,7 +31,7 @@ db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ }) ``` -GORM allows you setup FOREIGN KEY constraints's `OnDelete`, `OnUpdate` option with tag `constraint`, for example: +GORM vous permet de configurer les contraintes sur la clé étrangère avec `OnDelete`, `OnUpdate` avec le tag en option wit`constraint`, par exemple: ```go type User struct { diff --git a/pages/fr_FR/docs/create.md b/pages/fr_FR/docs/create.md index a8bd7a8fdf4..3cb92279b3b 100644 --- a/pages/fr_FR/docs/create.md +++ b/pages/fr_FR/docs/create.md @@ -1,5 +1,5 @@ --- -title: Create +title: Créer layout: page --- @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/fr_FR/docs/data_types.md b/pages/fr_FR/docs/data_types.md index d8acf63e3cd..c5694b866d4 100644 --- a/pages/fr_FR/docs/data_types.md +++ b/pages/fr_FR/docs/data_types.md @@ -1,11 +1,11 @@ --- -title: Customize Data Types +title: Personnaliser les types de données layout: page --- -GORM provides few interfaces that allow users to define well-supported customized data types for GORM, takes [json](https://github.com/go-gorm/datatypes/blob/master/json.go) as an example +GORM fournit quelques interfaces qui permettent aux utilisateurs de définir des types de données personnalisés bien pris en charge pour GORM, prend [json](https://github.com/go-gorm/datatypes/blob/master/json.go) comme exemple -## Implements Customized Data Type +## Implémenter de type de données personnalisées ### Scanner / Valuer diff --git a/pages/fr_FR/docs/dbresolver.md b/pages/fr_FR/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/fr_FR/docs/dbresolver.md +++ b/pages/fr_FR/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/fr_FR/docs/migration.md b/pages/fr_FR/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/fr_FR/docs/migration.md +++ b/pages/fr_FR/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/fr_FR/gen/database_to_structs.md b/pages/fr_FR/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/fr_FR/gen/database_to_structs.md +++ b/pages/fr_FR/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/fr_FR/gen/query.md b/pages/fr_FR/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/fr_FR/gen/query.md +++ b/pages/fr_FR/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/fr_FR/gen/rawsql_driver.html b/pages/fr_FR/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/fr_FR/gen/rawsql_driver.html +++ b/pages/fr_FR/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/fr_FR/rawsql.html b/pages/fr_FR/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/fr_FR/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/fr_FR/rawsql_driver.html b/pages/fr_FR/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/fr_FR/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/gen/rawsql_driver.html b/pages/gen/rawsql_driver.html new file mode 100644 index 00000000000..1a2a0d75540 --- /dev/null +++ b/pages/gen/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/gen + + diff --git a/pages/hi_IN/community.md b/pages/hi_IN/community.md index 1a8a94332af..028a345f1c7 100644 --- a/pages/hi_IN/community.md +++ b/pages/hi_IN/community.md @@ -42,6 +42,7 @@ layout: पृष्ठ * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Contribute to this page diff --git a/pages/hi_IN/docs/create.md b/pages/hi_IN/docs/create.md index 376e7544064..f80a342c842 100644 --- a/pages/hi_IN/docs/create.md +++ b/pages/hi_IN/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Selected फ़ील्ड्स के साथ रिकॉर्ड Create करे । Create a record and assign a value to the fields specified. diff --git a/pages/hi_IN/docs/dbresolver.md b/pages/hi_IN/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/hi_IN/docs/dbresolver.md +++ b/pages/hi_IN/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/hi_IN/docs/migration.md b/pages/hi_IN/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/hi_IN/docs/migration.md +++ b/pages/hi_IN/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/hi_IN/gen/database_to_structs.md b/pages/hi_IN/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/hi_IN/gen/database_to_structs.md +++ b/pages/hi_IN/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/hi_IN/gen/query.md b/pages/hi_IN/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/hi_IN/gen/query.md +++ b/pages/hi_IN/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/hi_IN/gen/rawsql_driver.html b/pages/hi_IN/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/hi_IN/gen/rawsql_driver.html +++ b/pages/hi_IN/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/hi_IN/rawsql.html b/pages/hi_IN/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/hi_IN/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/hi_IN/rawsql_driver.html b/pages/hi_IN/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/hi_IN/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/id_ID/community.md b/pages/id_ID/community.md index db1aa512c5c..5c261684090 100644 --- a/pages/id_ID/community.md +++ b/pages/id_ID/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Kontirbusi ke halamain ini diff --git a/pages/id_ID/docs/create.md b/pages/id_ID/docs/create.md index a8bd7a8fdf4..ce5544182c5 100644 --- a/pages/id_ID/docs/create.md +++ b/pages/id_ID/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/id_ID/docs/dbresolver.md b/pages/id_ID/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/id_ID/docs/dbresolver.md +++ b/pages/id_ID/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/id_ID/docs/migration.md b/pages/id_ID/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/id_ID/docs/migration.md +++ b/pages/id_ID/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/id_ID/gen/database_to_structs.md b/pages/id_ID/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/id_ID/gen/database_to_structs.md +++ b/pages/id_ID/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/id_ID/gen/query.md b/pages/id_ID/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/id_ID/gen/query.md +++ b/pages/id_ID/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/id_ID/gen/rawsql_driver.html b/pages/id_ID/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/id_ID/gen/rawsql_driver.html +++ b/pages/id_ID/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/id_ID/rawsql.html b/pages/id_ID/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/id_ID/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/id_ID/rawsql_driver.html b/pages/id_ID/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/id_ID/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/it_IT/community.md b/pages/it_IT/community.md index f5af60c1032..c1870d5b190 100644 --- a/pages/it_IT/community.md +++ b/pages/it_IT/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Contribute to this page diff --git a/pages/it_IT/docs/create.md b/pages/it_IT/docs/create.md index a8bd7a8fdf4..ce5544182c5 100644 --- a/pages/it_IT/docs/create.md +++ b/pages/it_IT/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/it_IT/docs/dbresolver.md b/pages/it_IT/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/it_IT/docs/dbresolver.md +++ b/pages/it_IT/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/it_IT/docs/migration.md b/pages/it_IT/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/it_IT/docs/migration.md +++ b/pages/it_IT/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/it_IT/gen/database_to_structs.md b/pages/it_IT/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/it_IT/gen/database_to_structs.md +++ b/pages/it_IT/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/it_IT/gen/query.md b/pages/it_IT/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/it_IT/gen/query.md +++ b/pages/it_IT/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/it_IT/gen/rawsql_driver.html b/pages/it_IT/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/it_IT/gen/rawsql_driver.html +++ b/pages/it_IT/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/it_IT/rawsql.html b/pages/it_IT/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/it_IT/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/it_IT/rawsql_driver.html b/pages/it_IT/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/it_IT/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/ja_JP/community.md b/pages/ja_JP/community.md index f7abc44ffdc..5103a9c5a77 100644 --- a/pages/ja_JP/community.md +++ b/pages/ja_JP/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## このページへの貢献 diff --git a/pages/ja_JP/docs/associations.md b/pages/ja_JP/docs/associations.md index cb8a575ce24..9ab1a933306 100644 --- a/pages/ja_JP/docs/associations.md +++ b/pages/ja_JP/docs/associations.md @@ -211,13 +211,13 @@ db.Model(&users).Association("Team").Append(&userA, &userB, &[]User{userA, userB db.Model(&users).Association("Team").Replace(&userA, &userB, &[]User{userA, userB, userC}) ``` -## Delete Association Record +## 関連レコードを削除する -By default, `Replace`/`Delete`/`Clear` in `gorm.Association` only delete the reference, that is, set old associations's foreign key to null. +デフォルトでは、`gorm.Association`の`Replace`/`Delete`/`Clear`は参照のみを削除します。つまり、古いアソシエーションの外部キーをNULLに設定します。 -You can delete those objects with `Unscoped` (it has nothing to do with `ManyToMany`). +`Unscoped`を使用することで、オブジェクトを削除することができます。(`ManyToMany`の場合は挙動に変更はありません) -How to delete is decided by `gorm.DB`. +削除方法は、 `gorm.DB` の内部で判定します。 ```go // Soft delete @@ -229,37 +229,37 @@ db.Model(&user).Association("Languages").Unscoped().Clear() db.Unscoped().Model(&item).Association("Languages").Unscoped().Clear() ``` -## Delete with Select +## Selectを使って削除する -You are allowed to delete selected has one/has many/many2many relations with `Select` when deleting records, for example: +レコード削除時に `Select` を使用することで、has one / has many / many2many 関係にある関連も同時に削除することができます。例: ```go -// delete user's account when deleting user +// ユーザ削除時に ユーザのアカウントも削除します db.Select("Account").Delete(&user) -// delete user's Orders, CreditCards relations when deleting user +// ユーザ削除時に ユーザの注文とクレジットカードの関連レコードも削除します db.Select("Orders", "CreditCards").Delete(&user) -// delete user's has one/many/many2many relations when deleting user +// ユーザ削除時に ユーザの全ての has one / has many / many2many の関連レコードも削除します db.Select(clause.Associations).Delete(&user) -// delete each user's account when deleting users +// 複数ユーザ削除時に それぞれのユーザのアカウントも削除します db.Select("Account").Delete(&users) ``` {% note warn %} -**NOTE:** Associations will only be deleted if the deleting records's primary key is not zero, GORM will use those primary keys as conditions to delete selected associations +**注意:** レコード削除時の主キーが非ゼロ値の場合のみ、関連レコードの削除が可能となります。GORMは指定の関連を削除するための条件として主キーを使用するためです。 ```go // DOESN'T WORK db.Select("Account").Where("name = ?", "jinzhu").Delete(&User{}) -// will delete all user with name `jinzhu`, but those user's account won't be deleted +// 名前が `jinzhu` である全てのユーザは削除されますが、ユーザのアカウントは削除されません db.Select("Account").Where("name = ?", "jinzhu").Delete(&User{ID: 1}) -// will delete the user with name = `jinzhu` and id = `1`, and user `1`'s account will be deleted +// 名前が `jinzhu` で id が `1` のユーザが削除され、そのユーザのアカウントも削除されます db.Select("Account").Delete(&User{ID: 1}) -// will delete the user with id = `1`, and user `1`'s account will be deleted +// id が `1` のユーザが削除され、そのユーザのアカウントも削除されます ``` {% endnote %} diff --git a/pages/ja_JP/docs/create.md b/pages/ja_JP/docs/create.md index f1b33bbf0f5..65903afff8f 100644 --- a/pages/ja_JP/docs/create.md +++ b/pages/ja_JP/docs/create.md @@ -28,16 +28,20 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## フィールドを選択してレコードを作成する -レコードを作成し、指定したフィールドに値を割り当てます。 +Create a record and assign a value to the fields specified. ```go db.Select("Name", "Age", "CreatedAt").Create(&user) // INSERT INTO `users` (`name`,`age`,`created_at`) VALUES ("jinzhu", 18, "2020-07-04 11:05:21.775") ``` -省略する項目を指定し、レコードを作成します。 +Create a record and ignore the values for fields passed to omit. ```go db.Omit("Name", "Age", "CreatedAt").Create(&user) @@ -46,7 +50,7 @@ db.Omit("Name", "Age", "CreatedAt").Create(&user) ## 一括作成 -大量のレコードを効率的に挿入するには、スライスを `Create` メソッドに渡します。 モデルのスライスをCreateメソッドに渡すと、GORMはすべてのデータを挿入する1つのSQL文を生成します。SQLが実行されると登録された主キーの値がモデルに代入され、フックメソッドも呼び出されます。 レコードが複数のバッチに分割されると、 **トランザクション** が開始されます。 +To efficiently insert large number of records, pass a slice to the `Create` method. GORM will generate a single SQL statement to insert all the data and backfill primary key values, hook methods will be invoked too. It will begin a **transaction** when records can be splited into multiple batches. ```go var users = []User{{Name: "jinzhu1"}, {Name: "jinzhu2"}, {Name: "jinzhu3"}} @@ -57,7 +61,7 @@ for _, user := range users { } ``` -`CreateInBatches` を利用して、バッチサイズを指定してレコードを作成できます。 +You can specify batch size when creating with `CreateInBatches`, e.g: ```go var users = []User{{Name: "jinzhu_1"}, ...., {Name: "jinzhu_10000"}} @@ -66,10 +70,10 @@ var users = []User{{Name: "jinzhu_1"}, ...., {Name: "jinzhu_10000"}} db.CreateInBatches(users, 100) ``` -[Upsert](#upsert) や [Create With Associations](#create_with_associations) を使用する場合もバッチインサートはサポートされています。 +Batch Insert is also supported when using [Upsert](#upsert) and [Create With Associations](#create_with_associations) {% note warn %} -**NOTE** `CreateBatchSize` オプションでGORMを初期化した場合、 `INSERT` メソッドはその設定を参照して、レコードを作成します。 +**NOTE** initialize GORM with `CreateBatchSize` option, all `INSERT` will respect this option when creating record & associations {% endnote %} ```go @@ -88,7 +92,7 @@ db.Create(&users) ## 作成時のHook -GORMでは、 `BeforeSave`, `BeforeCreate`, `AfterSave`, `AfterCreate`といったメソッドを実装することで、独自のHook処理を定義できます。 これらのメソッドはレコードを作成するときに呼び出されます。ライフサイクルの詳細については [Hooks](hooks.html) を参照してください。 +GORM allows user defined hooks to be implemented for `BeforeSave`, `BeforeCreate`, `AfterSave`, `AfterCreate`. These hook method will be called when creating a record, refer [Hooks](hooks.html) for details on the lifecycle ```go func (u *User) BeforeCreate(tx *gorm.DB) (err error) { @@ -101,7 +105,7 @@ func (u *User) BeforeCreate(tx *gorm.DB) (err error) { } ``` -`Hooks` メソッドをスキップしたい場合は、 `SkipHooks` セッションモードを使用できます。例: +If you want to skip `Hooks` methods, you can use the `SkipHooks` session mode, for example: ```go DB.Session(&gorm.Session{SkipHooks: true}).Create(&user) @@ -113,7 +117,7 @@ DB.Session(&gorm.Session{SkipHooks: true}).CreateInBatches(users, 100) ## Mapを使って作成する -GORMでは `map[string]interface{}` や `[]map[string]interface{}{}`を使ってレコード作成できます。例: +GORM supports create from `map[string]interface{}` and `[]map[string]interface{}{}`, e.g: ```go db.Model(&User{}).Create(map[string]interface{}{ @@ -128,12 +132,12 @@ db.Model(&User{}).Create([]map[string]interface{}{ ``` {% note warn %} -**注意** Mapを使用してレコードを作成する場合、Hookは呼び出されません。また、関連テーブルのレコードも保存されず、主キーの値もモデルに代入されません。 +**NOTE** When creating from map, hooks won't be invoked, associations won't be saved and primary key values won't be back filled {% endnote %} ## SQL式/Context Valuer で作成する -GORMはSQL式でデータを挿入することができます。これを行うには `map[string]interface{}` と [Customized Data Types](data_types.html#gorm_valuer_interface) の2つの方法があります。例: +GORM allows insert data with SQL expression, there are two ways to achieve this goal, create from `map[string]interface{}` or [Customized Data Types](data_types.html#gorm_valuer_interface), for example: ```go // Create from map @@ -180,7 +184,7 @@ db.Create(&User{ ### 関連データと関連付けて作成する -関連データと共にレコードを作成する場合、その値がゼロ値でなければ関連データもupsertされます。またその際には、関連データの `Hooks` メソッドも実行されます。 +When creating some data with associations, if its associations value is not zero-value, those associations will be upserted, and its `Hooks` methods will be invoked. ```go type CreditCard struct { @@ -203,7 +207,7 @@ db.Create(&User{ // INSERT INTO `credit_cards` ... ``` -`Select`, `Omit` を使うことで関連付けをスキップできます。例: +You can skip saving associations with `Select`, `Omit`, for example: ```go db.Omit("CreditCard").Create(&user) @@ -214,7 +218,7 @@ db.Omit(clause.Associations).Create(&user) ### デフォルト値 -`default`タグによって、フィールドのデフォルト値を定義できます。例: +You can define default values for fields with tag `default`, for example: ```go type User struct { @@ -224,10 +228,10 @@ type User struct { } ``` -データベースへの挿入時にフィールドが [ ゼロ値 ](https://tour.golang.org/basics/12) の場合、*デフォルト値が使用されます*。 +Then the default value *will be used* when inserting into the database for [zero-value](https://tour.golang.org/basics/12) fields {% note warn %} -**注意** デフォルト値を定義したフィールドには、 `0`, `''`, `false`のようなゼロ値はデータベースに保存されないため、これを避けるにはポインタ型やScanner/Valuerを使用するとよいでしょう。例: +**NOTE** Any zero value like `0`, `''`, `false` won't be saved into the database for those fields defined default value, you might want to use pointer type or Scanner/Valuer to avoid this, for example: {% endnote %} ```go @@ -240,7 +244,7 @@ type User struct { ``` {% note warn %} -**注意** データベース内でのデフォルト値、あるいは仮想の生成された値を持つフィールドには ` default ` タグを設定する必要があります。マイグレーション時にデフォルト値の定義をスキップする場合は、 `default:(-)`, 例: +**NOTE** You have to setup the `default` tag for fields having default or virtual/generated value in database, if you want to skip a default value definition when migrating, you could use `default:(-)`, for example: {% endnote %} ```go @@ -253,11 +257,11 @@ type User struct { } ``` -仮想の生成された値を使用する場合は、作成/更新権限を無効にする必要がある場合があります。 [Field-Level Permission](models.html#field_permission) を確認してください。 +When using virtual/generated value, you might need to disable its creating/updating permission, check out [Field-Level Permission](models.html#field_permission) ### コンフリクト発生時のUpsert -GORMは異なるデータベースに対して互換性のあるUpsertをサポートしています。 +GORM provides compatible Upsert support for different databases ```go import "gorm.io/gorm/clause" @@ -297,6 +301,6 @@ db.Clauses(clause.OnConflict{ // INSERT INTO `users` *** ON DUPLICATE KEY UPDATE `name`=VALUES(name),`age`=VALUES(age), ...; MySQL ``` -[Advanced Query](advanced_query.html) の `FirstOrInit`, `FirstOrCreate` も確認してみてください。 +Also checkout `FirstOrInit`, `FirstOrCreate` on [Advanced Query](advanced_query.html) -より詳細については、 [Raw SQL and SQL Builder](sql_builder.html) も参照してみてください。 +Checkout [Raw SQL and SQL Builder](sql_builder.html) for more details diff --git a/pages/ja_JP/docs/dbresolver.md b/pages/ja_JP/docs/dbresolver.md index 55411cf6474..704a7ccd978 100644 --- a/pages/ja_JP/docs/dbresolver.md +++ b/pages/ja_JP/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/ja_JP/docs/migration.md b/pages/ja_JP/docs/migration.md index 59d2da6e608..fb8f99abb06 100644 --- a/pages/ja_JP/docs/migration.md +++ b/pages/ja_JP/docs/migration.md @@ -265,13 +265,30 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details -## その他のマイグレーションツール +## Atlas Integration -GORMのAutoMigrateはほとんどのケースでうまく機能しますが、より本格的なスキーママイグレーションツールを利用する際は、GORMが提供している一般的なDBインターフェースが役に立ちます +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + +## Other Migration Tools + +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` db.DB() ``` -詳細については、 [Generic Interface](generic_interface.html) を参照してください。 +Refer to [Generic Interface](generic_interface.html) for more details. diff --git a/pages/ja_JP/gen/database_to_structs.md b/pages/ja_JP/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/ja_JP/gen/database_to_structs.md +++ b/pages/ja_JP/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/ja_JP/gen/query.md b/pages/ja_JP/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/ja_JP/gen/query.md +++ b/pages/ja_JP/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/ja_JP/gen/rawsql_driver.html b/pages/ja_JP/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/ja_JP/gen/rawsql_driver.html +++ b/pages/ja_JP/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/ja_JP/rawsql.html b/pages/ja_JP/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/ja_JP/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/ja_JP/rawsql_driver.html b/pages/ja_JP/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/ja_JP/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/ko_KR/community.md b/pages/ko_KR/community.md index afb90fdf2be..0448abbbe3e 100644 --- a/pages/ko_KR/community.md +++ b/pages/ko_KR/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## 이 페이지에 기여하세요 diff --git a/pages/ko_KR/docs/create.md b/pages/ko_KR/docs/create.md index 06ad1768290..1a8d719b861 100644 --- a/pages/ko_KR/docs/create.md +++ b/pages/ko_KR/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## 선택한 필드로 레코드 만들기 Create a record and assign a value to the fields specified. diff --git a/pages/ko_KR/docs/dbresolver.md b/pages/ko_KR/docs/dbresolver.md index fc5777f7f6d..ed5bfe828e9 100644 --- a/pages/ko_KR/docs/dbresolver.md +++ b/pages/ko_KR/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/ko_KR/docs/migration.md b/pages/ko_KR/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/ko_KR/docs/migration.md +++ b/pages/ko_KR/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/ko_KR/docs/models.md b/pages/ko_KR/docs/models.md index 441e3606c7e..207fa41289e 100644 --- a/pages/ko_KR/docs/models.md +++ b/pages/ko_KR/docs/models.md @@ -1,11 +1,11 @@ --- -title: Declaring Models +title: 모델 선언 layout: page --- -## Declaring Models +## 모델 선언 -Models are normal structs with basic Go types, pointers/alias of them or custom types implementing [Scanner](https://pkg.go.dev/database/sql/?tab=doc#Scanner) and [Valuer](https://pkg.go.dev/database/sql/driver#Valuer) interfaces +모델은 기본 Go 유형, 포인터/별칭 또는 [Scanner](https://pkg.go.dev/database/sql/?tab=doc#Scanner)및 [Valuer](https://pkg.go.dev/database/sql/driver#Valuer)인터페이스를 구현하는 사용자 정의 유형이 있는 일반 구조체입니다. 예를 들면 다음과 같습니다: @@ -23,11 +23,11 @@ type User struct { } ``` -## Conventions +## 규칙 -GORM prefers convention over configuration. By default, GORM uses `ID` as primary key, pluralizes struct name to `snake_cases` as table name, `snake_case` as column name, and uses `CreatedAt`, `UpdatedAt` to track creating/updating time +GORM은 구성보다 규칙을 선호합니다. 기본적으로 GORM은 `ID`를 기본 키로 사용하고, 복수형 `snake_cases`를 구조체 이름을 테이블 이름으로, `snake_case`를 열 이름으로, 생성/업데이트 시간을 추적하기 위해 `CreatedAt`, `UpdatedAt`을 사용합니다. -If you follow the conventions adopted by GORM, you'll need to write very little configuration/code. If convention doesn't match your requirements, [GORM allows you to configure them](conventions.html) +GORM에서 채택한 규칙을 따르는 경우 구성/코드를 거의 작성하지 않아도 됩니다. 규칙이 요구 사항과 일치하지 않는 경우 [GORM을 사용하여 규칙을 구성할 수 있습니다.](conventions.html) ## gorm.Model @@ -43,34 +43,32 @@ type Model struct { } ``` -해당 필드를 포함하도록 구조체를 만들 할 수 있습니다. [Embedded Struct를 참조하세요.](#embedded_struct) +해당 필드를 포함하도록 구조체를 만들 할 수 있습니다. [Embedded Struct](#embedded_struct)를 참조하세요. -## Advanced +## 고급 -### Field-Level Permission +### 필드 수준 권한 -Exported fields have all permissions when doing CRUD with GORM, and GORM allows you to change the field-level permission with tag, so you can make a field to be read-only, write-only, create-only, update-only or ignored +내보낸 필드는 GORM으로 CRUD를 수행할 때 모든 권한을 가지며, GORM에서는 태그를 사용하여 필드 수준 권한을 읽기 전용, 쓰기 전용, 만들기 전용, 업데이트 전용 또는 무시로 설정할 수 있습니다. {% note warn %} -**NOTE** ignored fields won't be created when using GORM Migrator to create table +**참고** GORM 마이그레이터를 사용하여 테이블을 만들 때 무시된 필드는 생성되지 않습니다. {% endnote %} ```go type User struct { - Name string `gorm:"<-:create"` // allow read and create - Name string `gorm:"<-:update"` // allow read and update - Name string `gorm:"<-"` // allow read and write (create and update) - Name string `gorm:"<-:false"` // allow read, disable write permission - Name string `gorm:"->"` // readonly (disable write permission unless it configured) - Name string `gorm:"->;<-:create"` // allow read and create - Name string `gorm:"->:false;<-:create"` // createonly (disabled read from db) - Name string `gorm:"-"` // ignore this field when write and read with struct - Name string `gorm:"-:all"` // ignore this field when write, read and migrate with struct - Name string `gorm:"-:migration"` // ignore this field when migrate with struct + Name string `gorm:"<-:create"` // 읽기/생성 허용 + Name string `gorm:"<-:update"` // 읽기/수정 허용 + Name string `gorm:"<-"` // 읽기/쓰기 허용 (생성 및 수정) + Name string `gorm:"<-:false"` // 읽기전용, 쓰기 불가능 + Name string `gorm:"->"` // 읽기허용 (설정되지 않은경우 쓰기 불가능) + Name string `gorm:"->;<-:create"` //읽기/생성 허용 + Name string `gorm:"->:false;<-:create"` // 생성만 가능 (읽기 불가능) + Name string `gorm:"-"` // gorm 에서 이 필드 무시 } ``` -### Creating/Updating Time/Unix (Milli/Nano) Seconds Tracking +### Creating/Updating Time/Unix (Milli/Nano) Seconds Tracking 생성/업데이트 시 시간/유닉스시간(밀리/나노) 기록 GORM use `CreatedAt`, `UpdatedAt` to track creating/updating time by convention, and GORM will set the [current time](gorm_config.html#now_func) when creating/updating if the fields are defined diff --git a/pages/ko_KR/docs/query.md b/pages/ko_KR/docs/query.md index 504265fb857..26d7b9e8e43 100644 --- a/pages/ko_KR/docs/query.md +++ b/pages/ko_KR/docs/query.md @@ -1,5 +1,5 @@ --- -title: 선택 +title: 질의문 layout: 페이지 --- @@ -33,10 +33,10 @@ errors.Is(result.Error, gorm.ErrRecordNotFound) {% 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 +단일 객체 제한 `db.Find(&user)` 없이 `Find` 메서드를 사용하는 것은 테이블 전체 조회하고 오로지 첫번째 객체만이 반환될 것입니다. 이것은 효율적이지 않으며 비결정적입니다. {% 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: +`First` 와 `Last` 메서드는 기본키 정렬 기준으로 각각 첫번째와 마지막 레코드를 조회합니다. 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: ```go var user User diff --git a/pages/ko_KR/gen/database_to_structs.md b/pages/ko_KR/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/ko_KR/gen/database_to_structs.md +++ b/pages/ko_KR/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/ko_KR/gen/query.md b/pages/ko_KR/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/ko_KR/gen/query.md +++ b/pages/ko_KR/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/ko_KR/gen/rawsql_driver.html b/pages/ko_KR/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/ko_KR/gen/rawsql_driver.html +++ b/pages/ko_KR/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/ko_KR/rawsql.html b/pages/ko_KR/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/ko_KR/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/ko_KR/rawsql_driver.html b/pages/ko_KR/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/ko_KR/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/pl_PL/community.md b/pages/pl_PL/community.md index e2aa1522715..09a23e446cd 100644 --- a/pages/pl_PL/community.md +++ b/pages/pl_PL/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Współtwórz tę stronę diff --git a/pages/pl_PL/docs/create.md b/pages/pl_PL/docs/create.md index a8bd7a8fdf4..ce5544182c5 100644 --- a/pages/pl_PL/docs/create.md +++ b/pages/pl_PL/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Create Record With Selected Fields Create a record and assign a value to the fields specified. diff --git a/pages/pl_PL/docs/dbresolver.md b/pages/pl_PL/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/pl_PL/docs/dbresolver.md +++ b/pages/pl_PL/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/pl_PL/docs/migration.md b/pages/pl_PL/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/pl_PL/docs/migration.md +++ b/pages/pl_PL/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/pl_PL/gen/database_to_structs.md b/pages/pl_PL/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/pl_PL/gen/database_to_structs.md +++ b/pages/pl_PL/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/pl_PL/gen/query.md b/pages/pl_PL/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/pl_PL/gen/query.md +++ b/pages/pl_PL/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/pl_PL/gen/rawsql_driver.html b/pages/pl_PL/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/pl_PL/gen/rawsql_driver.html +++ b/pages/pl_PL/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/pl_PL/rawsql.html b/pages/pl_PL/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/pl_PL/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/pl_PL/rawsql_driver.html b/pages/pl_PL/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/pl_PL/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/pt_BR/community.md b/pages/pt_BR/community.md index f951a49a8f4..ac8053a8248 100644 --- a/pages/pt_BR/community.md +++ b/pages/pt_BR/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - Plugin de cache de consultas para o GORM](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Contribua para esta página diff --git a/pages/pt_BR/docs/associations.md b/pages/pt_BR/docs/associations.md index 8832a4c67cf..6d20df088e1 100644 --- a/pages/pt_BR/docs/associations.md +++ b/pages/pt_BR/docs/associations.md @@ -186,7 +186,7 @@ codes := []string{"zh-CN", "en-US", "ja-JP"} db.Model(&user).Where("code IN ?", codes).Association("Languages").Count() ``` -### Lote de dados +### Lote de Dados Modo de associação suporta dados em lote, por exemplo: @@ -208,59 +208,59 @@ db.Model(&users).Association("Team").Append(&userA, &userB, &[]User{userA, userB db.Model(&users).Association("Team").Replace(&userA, &userB, &[]User{userA, userB, userC}) ``` -## Delete Association Record +## Apagar Registro de Associação -By default, `Replace`/`Delete`/`Clear` in `gorm.Association` only delete the reference, that is, set old associations's foreign key to null. +Por padrão, `Replace`/`Delete`/`Clear` em `gorm.Association` apenas deletam a referência, ou seja, definem a chave estrangeira das associações antigas como nula. -You can delete those objects with `Unscoped` (it has nothing to do with `ManyToMany`). +Você pode excluir esses objetos com `Unscoped` (isso não tem nada a ver com `ManyToMany`). -How to delete is decided by `gorm.DB`. +Como excluir é decidido por `gorm.DB`. ```go -// Soft delete +// Exclusão reversível // UPDATE `languages` SET `deleted_at`= ... db.Model(&user).Association("Languages").Unscoped().Clear() -// Delete permanently +// Apagar permanentemente // DELETE FROM `languages` WHERE ... db.Unscoped().Model(&item).Association("Languages").Unscoped().Clear() ``` -## Delete with Select +## Excluir com Select -You are allowed to delete selected has one/has many/many2many relations with `Select` when deleting records, for example: +É permitido excluir relações selecionadas de has one/has many/many2many usando `Select` ao deletar registros, por exemplo: ```go -// delete user's account when deleting user +// excluir a conta do usuário ao excluir o usuário db.Select("Account").Delete(&user) -// delete user's Orders, CreditCards relations when deleting user +// excluir as relações de Pedidos e CartoesDeCredito do usuário ao deletar o usuário db.Select("Orders", "CreditCards").Delete(&user) -// delete user's has one/many/many2many relations when deleting user +// excluir as relações "has one/many/many2many" do usuário ao deletar o usuário db.Select(clause.Associations).Delete(&user) -// delete each user's account when deleting users +// excluir a conta de cada usuário ao deletar os usuários db.Select("Account").Delete(&users) ``` {% note warn %} -**NOTE:** Associations will only be deleted if the deleting records's primary key is not zero, GORM will use those primary keys as conditions to delete selected associations +**Nota:** As associações serão excluídas somente se a chave primária dos registros a serem excluídos não for zero. O GORM usará essas chaves primárias como condições para excluir as associações selecionadas ```go -// DOESN'T WORK +// NÃO FUNCIONA db.Select("Account").Where("name = ?", "jinzhu").Delete(&User{}) -// will delete all user with name `jinzhu`, but those user's account won't be deleted +// irá excluir todos os usuários com o nome `jinzhu`, mas as contas desses usuários não serão excluídas db.Select("Account").Where("name = ?", "jinzhu").Delete(&User{ID: 1}) -// will delete the user with name = `jinzhu` and id = `1`, and user `1`'s account will be deleted +// irá excluir o usuário com o nome `jinzhu` e id = `1`, e a conta do usuário `1` será excluída db.Select("Account").Delete(&User{ID: 1}) -// will delete the user with id = `1`, and user `1`'s account will be deleted +// irá excluir o usuário com id = `1`, e a conta do usuário `1` será excluída ``` {% endnote %} -## Association Tags +## Associação de Tags | Tag | Descrição | | ---------------- | -------------------------------------------------------------------------------------------------------------- | diff --git a/pages/pt_BR/docs/context.md b/pages/pt_BR/docs/context.md index 536f4a2b2c3..3d6e68decf6 100644 --- a/pages/pt_BR/docs/context.md +++ b/pages/pt_BR/docs/context.md @@ -3,9 +3,9 @@ title: Contexto layout: page --- -GORM provides Context support, you can use it with method `WithContext` +GORM fornece suporte a contextos, você pode usá-lo com o método `WithContext` -## Single Session Mode +## Modo de sessão única Single session mode usually used when you want to perform a single operation diff --git a/pages/pt_BR/docs/create.md b/pages/pt_BR/docs/create.md index 717f11b46c3..83597146b2f 100644 --- a/pages/pt_BR/docs/create.md +++ b/pages/pt_BR/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Criar registro com campos selecionados Create a record and assign a value to the fields specified. diff --git a/pages/pt_BR/docs/dbresolver.md b/pages/pt_BR/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/pt_BR/docs/dbresolver.md +++ b/pages/pt_BR/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/pt_BR/docs/migration.md b/pages/pt_BR/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/pt_BR/docs/migration.md +++ b/pages/pt_BR/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/pt_BR/gen/database_to_structs.md b/pages/pt_BR/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/pt_BR/gen/database_to_structs.md +++ b/pages/pt_BR/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/pt_BR/gen/query.md b/pages/pt_BR/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/pt_BR/gen/query.md +++ b/pages/pt_BR/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/pt_BR/gen/rawsql_driver.html b/pages/pt_BR/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/pt_BR/gen/rawsql_driver.html +++ b/pages/pt_BR/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/pt_BR/rawsql.html b/pages/pt_BR/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/pt_BR/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/pt_BR/rawsql_driver.html b/pages/pt_BR/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/pt_BR/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/rawsql_driver.html b/pages/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/ru_RU/community.md b/pages/ru_RU/community.md index e413bb8b510..9f027e10a70 100644 --- a/pages/ru_RU/community.md +++ b/pages/ru_RU/community.md @@ -42,6 +42,7 @@ layout: страница * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Внести изменения в эту страницу diff --git a/pages/ru_RU/docs/create.md b/pages/ru_RU/docs/create.md index ff816967d18..7b63ed27401 100644 --- a/pages/ru_RU/docs/create.md +++ b/pages/ru_RU/docs/create.md @@ -28,16 +28,20 @@ result.Error // возвращает ошибку result.RowsAffected // возвращает количество добавленных записей ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Создание записи с указанными полями -Создаем запись и присваиваем значение указанным полям. +Create a record and assign a value to the fields specified. ```go db.Select("Name", "Age", "CreatedAt").Create(&user) // INSERT INTO `users` (`name`,`age`,`created_at`) VALUES ("jinzhu", 18, "2020-07-04 11:05:21.775") ``` -Создайте запись и игнорируйте значения для полей, переданных в пропущенные (omit). +Create a record and ignore the values for fields passed to omit. ```go db.Omit("Name", "Age", "CreatedAt").Create(&user) @@ -46,7 +50,7 @@ db.Omit("Name", "Age", "CreatedAt").Create(&user) ## Пакетная вставка -Чтобы эффективно вставить большое количество записей, передайте срез в метод `Create`. Передайте массив с данными в метод Create, GORM создаст запрос SQL для вставки и заполнит первичными ключами массив, будут также вызваны хук методы. При это начнется **транзакция**, когда записи могут быть переданы в несколько партий. +To efficiently insert large number of records, pass a slice to the `Create` method. GORM will generate a single SQL statement to insert all the data and backfill primary key values, hook methods will be invoked too. It will begin a **transaction** when records can be splited into multiple batches. ```go var users = []User{{Name: "jinzhu1"}, {Name: "jinzhu2"}, {Name: "jinzhu3"}} @@ -57,7 +61,7 @@ for _, user := range users { } ``` -Вы можете указать размер пакета при создании с помощью `CreateInBatches`, например: +You can specify batch size when creating with `CreateInBatches`, e.g: ```go var users = []User{{Name: "jinzhu_1"}, ...., {Name: "jinzhu_10000"}} @@ -66,10 +70,10 @@ var users = []User{{Name: "jinzhu_1"}, ...., {Name: "jinzhu_10000"}} db.CreateInBatches(users, 100) ``` -Пакетная вставка также поддерживается при использовании [Upsert](#upsert) и [Создания с помощью ассоциаций](#create_with_associations) +Batch Insert is also supported when using [Upsert](#upsert) and [Create With Associations](#create_with_associations) {% note warn %} -**ПРИМЕЧАНИЕ** инициализируйте GORM с помощью параметра `CreateBatchSize`, все `INSERT` будут учитывать этот параметр при создании записей и ассоциаций +**NOTE** initialize GORM with `CreateBatchSize` option, all `INSERT` will respect this option when creating record & associations {% endnote %} ```go @@ -88,7 +92,7 @@ db.Create(&users) ## Создание хуков -GORM позволяет реализовать пользовательские хуки для `BeforeSave`, `BeforeCreate`, `AfterSave` и `AfterCreate`. Этот метод перехвата будет вызван при создании записи, обратитесь к [Хуки](hooks.html) для получения подробной информации о жизненном цикле +GORM allows user defined hooks to be implemented for `BeforeSave`, `BeforeCreate`, `AfterSave`, `AfterCreate`. These hook method will be called when creating a record, refer [Hooks](hooks.html) for details on the lifecycle ```go func (u *User) BeforeCreate(tx *gorm.DB) (err error) { @@ -101,7 +105,7 @@ func (u *User) BeforeCreate(tx *gorm.DB) (err error) { } ``` -Если вы хотите пропустить `Хуки`, вы можете использовать режим сеанса `SkipHooks`, например: +If you want to skip `Hooks` methods, you can use the `SkipHooks` session mode, for example: ```go DB.Session(&gorm.Session{SkipHooks: true}).Create(&user) @@ -113,7 +117,7 @@ DB.Session(&gorm.Session{SkipHooks: true}).CreateInBatches(users, 100) ## Create с помощью Map(карты) -GORM поддерживает создание из `map[string]interface{}` и `[]map[string]interface{}{}`, например: +GORM supports create from `map[string]interface{}` and `[]map[string]interface{}{}`, e.g: ```go db.Model(&User{}).Create(map[string]interface{}{ @@ -128,12 +132,12 @@ db.Model(&User{}).Create([]map[string]interface{}{ ``` {% note warn %} -**ПРИМЕЧАНИЕ** При создании на основе карты не будут вызываться хуки, ассоциации не будут сохранены, а значения первичного ключа не будут заполнены обратно +**NOTE** When creating from map, hooks won't be invoked, associations won't be saved and primary key values won't be back filled {% endnote %} ## Метод Create с помощью SQL выражения/значения контекста -GORM позволяет вставлять данные с помощью SQL-выражения, есть два способа достичь этой цели, создать из `map[string]interface{}` или [Настраиваемые типы данных](data_types.html#gorm_valuer_interface), например: +GORM allows insert data with SQL expression, there are two ways to achieve this goal, create from `map[string]interface{}` or [Customized Data Types](data_types.html#gorm_valuer_interface), for example: ```go // Создать из map @@ -180,7 +184,7 @@ db.Create(&User{ ### Create со связями -При создании некоторых данных с ассоциациями, если их значение не равно нулю, эти ассоциации будут обновлены, и будут вызваны его `Хуки`. +When creating some data with associations, if its associations value is not zero-value, those associations will be upserted, and its `Hooks` methods will be invoked. ```go type CreditCard struct { @@ -203,7 +207,7 @@ db.Create(&User{ // INSERT INTO `credit_cards` ... ``` -Вы можете пропустить сохранение ассоциаций с помощью `Select`, `Omit`, например: +You can skip saving associations with `Select`, `Omit`, for example: ```go db.Omit("CreditCard").Create(&user) @@ -214,7 +218,7 @@ db.Omit(clause.Associations).Create(&user) ### Значения по умолчанию -Вы можете определить значения по умолчанию для полей с тегом `default`, например: +You can define default values for fields with tag `default`, for example: ```go type User struct { @@ -224,10 +228,10 @@ type User struct { } ``` -Тогда значение по умолчанию * будет использоваться* при вставке в базу данных для [полей с нулевым значением](https://tour.golang.org/basics/12) +Then the default value *will be used* when inserting into the database for [zero-value](https://tour.golang.org/basics/12) fields {% note warn %} -**ПРИМЕЧАНИЕ** Любое нулевое значение, например `0`, `"`, `false`, не будет сохранено в базе данных для этих полей, определенных значением по умолчанию, вы можете захотеть использовать тип указателя или Scanner / Valuer, чтобы избежать этого, например: +**NOTE** Any zero value like `0`, `''`, `false` won't be saved into the database for those fields defined default value, you might want to use pointer type or Scanner/Valuer to avoid this, for example: {% endnote %} ```go @@ -240,7 +244,7 @@ type User struct { ``` {% note warn %} -**ПРИМЕЧАНИЕ** Вам необходимо настроить тег `default` для полей, имеющих значение по умолчанию или виртуальное/сгенерированное значение в базе данных, если вы хотите пропустить определение значения по умолчанию при миграции, вы могли бы использовать `default:(-)`, например: +**NOTE** You have to setup the `default` tag for fields having default or virtual/generated value in database, if you want to skip a default value definition when migrating, you could use `default:(-)`, for example: {% endnote %} ```go @@ -253,11 +257,11 @@ type User struct { } ``` -При использовании виртуального/сгенерированного значения вам может потребоваться отключить разрешение на его создание/обновление, проверьте [Разрешение на уровне поля](models.html#field_permission) +When using virtual/generated value, you might need to disable its creating/updating permission, check out [Field-Level Permission](models.html#field_permission) ### Upsert (Создать или обновить) / При конфликте -GORM обеспечивает совместимую поддержку Upsert для различных баз данных +GORM provides compatible Upsert support for different databases ```go import "gorm.io/gorm/clause" @@ -297,6 +301,6 @@ db.Clauses(clause.OnConflict{ // INSERT INTO `users` *** ON DUPLICATE KEY UPDATE `name`=VALUES(name),`age`=VALUES(age), ...; MySQL ``` -Также посмотрите `FirstOrInit`, `FirstOrCreate` на [Расширенный запрос](advanced_query.html) +Also checkout `FirstOrInit`, `FirstOrCreate` on [Advanced Query](advanced_query.html) -Откройте [Необработанный SQL и SQL Builder](sql_builder.html) для получения более подробной информации +Checkout [Raw SQL and SQL Builder](sql_builder.html) for more details diff --git a/pages/ru_RU/docs/dbresolver.md b/pages/ru_RU/docs/dbresolver.md index 433d1877281..b0e27fc5ad0 100644 --- a/pages/ru_RU/docs/dbresolver.md +++ b/pages/ru_RU/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/ru_RU/docs/hints.md b/pages/ru_RU/docs/hints.md index 52dd20bdb7a..399e0cb464c 100644 --- a/pages/ru_RU/docs/hints.md +++ b/pages/ru_RU/docs/hints.md @@ -13,7 +13,7 @@ https://github.com/go-gorm/hints import "gorm.io/hints" db.Clauses(hints.New("hint")).Find(&User{}) -// SELECT * /*+ hint */ FROM `users` +// SELECT * /*+ подсказка */ FROM `users` ``` ## Подсказки индексирования diff --git a/pages/ru_RU/docs/migration.md b/pages/ru_RU/docs/migration.md index 5a3a24ffffa..1029b73f51f 100644 --- a/pages/ru_RU/docs/migration.md +++ b/pages/ru_RU/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details -## Другие инструменты миграции +## Atlas Integration -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + +## Other Migration Tools + +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/ru_RU/gen/database_to_structs.md b/pages/ru_RU/gen/database_to_structs.md index 6523b66c3e4..319e52097ca 100644 --- a/pages/ru_RU/gen/database_to_structs.md +++ b/pages/ru_RU/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/ru_RU/gen/query.md b/pages/ru_RU/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/ru_RU/gen/query.md +++ b/pages/ru_RU/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/ru_RU/gen/rawsql_driver.html b/pages/ru_RU/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/ru_RU/gen/rawsql_driver.html +++ b/pages/ru_RU/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/ru_RU/rawsql.html b/pages/ru_RU/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/ru_RU/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/ru_RU/rawsql_driver.html b/pages/ru_RU/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/ru_RU/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/tr_TR/community.md b/pages/tr_TR/community.md index d5613ba0b61..88b3d0f0640 100644 --- a/pages/tr_TR/community.md +++ b/pages/tr_TR/community.md @@ -42,6 +42,7 @@ layout: sayfa * [gorm-cache - GORM query cache plugin](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM Helper - GORM Code Completion Goland Plugin](https://github.com/maiqingqiang/go-orm-helper) ## Bu sayfaya katkıda bulunmak diff --git a/pages/tr_TR/docs/create.md b/pages/tr_TR/docs/create.md index 3cd5b9a0ca5..d77603d7f75 100644 --- a/pages/tr_TR/docs/create.md +++ b/pages/tr_TR/docs/create.md @@ -28,6 +28,10 @@ result.Error // returns error result.RowsAffected // returns inserted records count ``` +{% note warn %} +**NOTE** You cannot pass a struct to 'create', so you should pass a pointer to the data. +{% endnote %} + ## Seçilen Alanlarla Kayıt Oluştur Create a record and assign a value to the fields specified. diff --git a/pages/tr_TR/docs/dbresolver.md b/pages/tr_TR/docs/dbresolver.md index 2d67fe05322..2fe2aa9db18 100644 --- a/pages/tr_TR/docs/dbresolver.md +++ b/pages/tr_TR/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/tr_TR/docs/delete.md b/pages/tr_TR/docs/delete.md index c4a142cdd20..9695fdfdf76 100644 --- a/pages/tr_TR/docs/delete.md +++ b/pages/tr_TR/docs/delete.md @@ -5,21 +5,21 @@ layout: sayfa ## Bir Kaydı Sil -When deleting a record, the deleted value needs to have primary key or it will trigger a [Batch Delete](#batch_delete), for example: +Bir kaydı silerken, silinen değerin birincil anahtara sahip olması gerekir, aksi takdirde [toplu silme](#batch_delete) işlemini tetiklenir. Örneğin: ```go -// Email's ID is `10` +// Email Id değerimizin '10' olduğunu varsayalım db.Delete(&email) // DELETE from emails where id = 10; -// Delete with additional conditions +// Koşul belirterek silme işlemi db.Where("name = ?", "jinzhu").Delete(&email) // DELETE from emails where id = 10 AND name = "jinzhu"; ``` ## Birincil anahtar ile sil -GORM allows to delete objects using primary key(s) with inline condition, it works with numbers, check out [Query Inline Conditions](query.html#inline_conditions) for details +GORM, satır içi koşul ile birincil anahtar(lar) kullanarak nesneleri silmeye izin verir, sayılarla çalışır, ayrıntılar için [Satır içi koşullar](query.html#inline_conditions) bölümüne göz atın ```go db.Delete(&User{}, 10) @@ -32,22 +32,22 @@ db.Delete(&users, []int{1,2,3}) // DELETE FROM users WHERE id IN (1,2,3); ``` -## Delete Hooks +## Hook ile Silme -GORM allows hooks `BeforeDelete`, `AfterDelete`, those methods will be called when deleting a record, refer [Hooks](hooks.html) for details +GORM,`BeforeDelete`, `AfterDelete` hooklarına izin verir, bu yöntemler bir kayıt silinirken çağrılacaktır, ayrıntılar için [Hooks](hooks.html) sayfasına bakınız ```go func (u *User) BeforeDelete(tx *gorm.DB) (err error) { if u.Role == "admin" { - return errors.New("admin user not allowed to delete") + return errors.New("admin kullanıcısının silme yetkisi yok") } return } ``` -## Batch Delete +## Toplu Silme -The specified value has no primary value, GORM will perform a batch delete, it will delete all matched records +Belirtilen değerin birincil değeri yoksa, GORM bir toplu silme işlemi gerçekleştirir, koşulla eşleşen tüm kayıtları siler ```go db.Where("email LIKE ?", "%jinzhu%").Delete(&Email{}) @@ -57,7 +57,7 @@ db.Delete(&Email{}, "email LIKE ?", "%jinzhu%") // DELETE from emails where email LIKE "%jinzhu%"; ``` -To efficiently delete large number of records, pass a slice with primary keys to the `Delete` method. +Çok sayıda kaydı verimli bir şekilde silmek için, `Delete` yöntemine birincil anahtarları içeren bir slice ekleyin. ```go var users = []User{{ID: 1}, {ID: 2}, {ID: 3}} @@ -68,16 +68,16 @@ db.Delete(&users, "name LIKE ?", "%jinzhu%") // DELETE FROM users WHERE name LIKE "%jinzhu%" AND id IN (1,2,3); ``` -### Block Global Delete +### Global Silme İşlemini Engelleme -If you perform a batch delete without any conditions, GORM WON'T run it, and will return `ErrMissingWhereClause` error +Herhangi bir koşul olmadan bir toplu silme işlemi gerçekleştirirseniz, GORM bunu çalıştırmaz ve `ErrMissingWhereClause` hatası döndürür -You have to use some conditions or use raw SQL or enable `AllowGlobalUpdate` mode, for example: +Eğer kullanmak istiyorsanız, bazı koşulları eklemelisiniz, Saf (Raw) SQL sorgusu kullanmalısınız veya `AllowGlobalUpdate` modunu aktif etmeniz gerekiyor. Örneğin: ```go -db.Delete(&User{}).Error // gorm.ErrMissingWhereClause +db.Delete(&User{}).Error // gorm.ErrMissingWhereClause hatası döndürür. -db.Delete(&[]User{{Name: "jinzhu1"}, {Name: "jinzhu2"}}).Error // gorm.ErrMissingWhereClause +db.Delete(&[]User{{Name: "jinzhu1"}, {Name: "jinzhu2"}}).Error // gorm.ErrMissingWhereClause hatası döndürür. db.Where("1 = 1").Delete(&User{}) // DELETE FROM `users` WHERE 1=1 @@ -89,44 +89,44 @@ db.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&User{}) // DELETE FROM users ``` -### Returning Data From Deleted Rows +### Silinen Satırlardan Veri Döndürme -Return deleted data, only works for database support Returning, for example: +Silinen verileri döndür, yalnızca destekleyen veritabanları için döndürür, Örneğin: ```go -// return all columns +// Bütün sütunları döndürür var users []User DB.Clauses(clause.Returning{}).Where("role = ?", "admin").Delete(&users) // DELETE FROM `users` WHERE role = "admin" RETURNING * // users => []User{{ID: 1, Name: "jinzhu", Role: "admin", Salary: 100}, {ID: 2, Name: "jinzhu.2", Role: "admin", Salary: 1000}} -// return specified columns +// Belirtilen sütunları döndürür DB.Clauses(clause.Returning{Columns: []clause.Column{{Name: "name"}, {Name: "salary"}}}).Where("role = ?", "admin").Delete(&users) // DELETE FROM `users` WHERE role = "admin" RETURNING `name`, `salary` // users => []User{{ID: 0, Name: "jinzhu", Role: "", Salary: 100}, {ID: 0, Name: "jinzhu.2", Role: "", Salary: 1000}} ``` -## Soft Delete +## Geçici Silme -If your model includes a `gorm.DeletedAt` field (which is included in `gorm.Model`), it will get soft delete ability automatically! +Modeliniz bir `gorm.DeletedAt` alanı içeriyorsa (`gorm.Model` içinde yer alır), otomatik olarak geçici silme özelliğine sahip olur! -When calling `Delete`, the record WON'T be removed from the database, but GORM will set the `DeletedAt`'s value to the current time, and the data is not findable with normal Query methods anymore. +`Delete` çağrıldığında, kayıt veritabanından kaldırılmaz, ancak GORM `DeletedAt`'ın değerine silinme tarihi atanır. Veriler sorgularınızda gözükmezler. ```go // user's ID is `111` db.Delete(&user) // UPDATE users SET deleted_at="2013-10-29 10:23" WHERE id = 111; -// Batch Delete +// Toplu Silme db.Where("age = ?", 20).Delete(&User{}) // UPDATE users SET deleted_at="2013-10-29 10:23" WHERE age = 20; -// Soft deleted records will be ignored when querying +// Sorgulama sırasında geçici silinen kayıtlar yok sayılır db.Where("age = 20").Find(&user) // SELECT * FROM users WHERE age = 20 AND deleted_at IS NULL; ``` -If you don't want to include `gorm.Model`, you can enable the soft delete feature like: +`gorm.Model`'i dahil etmek istemiyorsanız, geçici silmeyi modelinize ekleyebilirsiniz. Örneğin: ```go type User struct { @@ -136,18 +136,18 @@ type User struct { } ``` -### Find soft deleted records +### Geçici silinmiş kayıtların bulunması -You can find soft deleted records with `Unscoped` +Geçici silinen kayıtları `Unscoped` ile bulabilirsiniz ```go db.Unscoped().Where("age = 20").Find(&users) // SELECT * FROM users WHERE age = 20; ``` -### Delete permanently +### Kalıcı Olarak Sil -You can delete matched records permanently with `Unscoped` +`Unscoped` ile eşleşen kayıtları kalıcı olarak silebilirsiniz ```go db.Unscoped().Delete(&order) @@ -156,10 +156,10 @@ db.Unscoped().Delete(&order) ### Delete Flag -By default, `gorm.Model` uses `*time.Time` as the value for the `DeletedAt` field, and it provides other data formats support with plugin `gorm.io/plugin/soft_delete` +Varsayılan olarak, `gorm.Model` `DeletedAt` alanı için değer olarak `*time.Time` kullanır.`gorm.io/plugin/soft_delete` eklentisi ise diğer veri türleri içinde destek sağlar {% note warn %} -**INFO** when creating unique composite index for the DeletedAt field, you must use other data format like unix second/flag with plugin `gorm.io/plugin/soft_delete`'s help, e.g: +**INFO** DeletedAt alanı için benzersiz bileşik dizin oluştururken, `gorm.io/plugin/soft_delete` eklentisinin yardımıyla unix second/flag gibi diğer veri türleri kullanmalısınız, örn: ```go import "gorm.io/plugin/soft_delete" @@ -172,9 +172,9 @@ type User struct { ``` {% endnote %} -#### Unix Second +#### Unix Zamanı (Epoch veya Posix) -Use unix second as delete flag +Delete Flag'de unix zamanı kullanma ```go import "gorm.io/plugin/soft_delete" @@ -192,7 +192,7 @@ SELECT * FROM users WHERE deleted_at = 0; UPDATE users SET deleted_at = /* current unix second */ WHERE ID = 1; ``` -You can also specify to use `milli` or `nano` seconds as the value, for example: +Değer olarak örneğin `milli` veya `nano` saniye kullanılmasını da belirtebilirsiniz: ```go type User struct { @@ -206,10 +206,10 @@ type User struct { SELECT * FROM users WHERE deleted_at = 0; // Delete -UPDATE users SET deleted_at = /* current unix milli second or nano second */ WHERE ID = 1; +UPDATE users SET deleted_at = /* geçerli zamana ait unix mili saniyesi veya nano saniyesi */ WHERE ID = 1; ``` -#### Use `1` / `0` AS Delete Flag +#### Delete Flag olarak `1` / `0` kullanılması ```go import "gorm.io/plugin/soft_delete" @@ -227,9 +227,9 @@ SELECT * FROM users WHERE is_del = 0; UPDATE users SET is_del = 1 WHERE ID = 1; ``` -#### Mixed Mode +#### Karışık Mod -Mixed mode can use `0`, `1` or unix seconds to mark data as deleted or not, and save the deleted time at the same time. +Karma mod, verileri silinmiş veya silinmemiş olarak işaretlemek ve aynı zamanda silinen zamanı kaydetmek için `0`, `1` veya unix saniye kullanabilir. ```go type User struct { diff --git a/pages/tr_TR/docs/migration.md b/pages/tr_TR/docs/migration.md index c78fb16fc73..214215a1a51 100644 --- a/pages/tr_TR/docs/migration.md +++ b/pages/tr_TR/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details +## Atlas Integration + +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + ## Other Migration Tools -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/tr_TR/gen/database_to_structs.md b/pages/tr_TR/gen/database_to_structs.md index 89e82f8a3da..8fd89393272 100644 --- a/pages/tr_TR/gen/database_to_structs.md +++ b/pages/tr_TR/gen/database_to_structs.md @@ -247,3 +247,49 @@ Specify datatype mapping between field type and db column type. g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/tr_TR/gen/query.md b/pages/tr_TR/gen/query.md index 2bc6ba1bfec..fd26cd256fa 100644 --- a/pages/tr_TR/gen/query.md +++ b/pages/tr_TR/gen/query.md @@ -505,6 +505,7 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` @@ -516,7 +517,7 @@ Get first matched record or create a new one with given conditions (only works w ```go // Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) +result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() // user -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go diff --git a/pages/tr_TR/gen/rawsql_driver.html b/pages/tr_TR/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/tr_TR/gen/rawsql_driver.html +++ b/pages/tr_TR/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/tr_TR/rawsql.html b/pages/tr_TR/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/tr_TR/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/tr_TR/rawsql_driver.html b/pages/tr_TR/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/tr_TR/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/pages/zh_CN/community.md b/pages/zh_CN/community.md index c04e427f75e..e4969dc6a55 100644 --- a/pages/zh_CN/community.md +++ b/pages/zh_CN/community.md @@ -42,6 +42,7 @@ layout: page * [gorm-cache - GORM 查询缓存插件](https://github.com/liyuan1125/gorm-cache) * [deepgorm - Nested map filtering](https://github.com/survivorbat/gorm-deep-filtering) * [oracle - GORM Oracle driver](https://github.com/CengSin/oracle) +* [Go ORM 助手 - GORM 代码补全 Goland 插件](https://github.com/maiqingqiang/go-orm-helper) ## 完善本页面 diff --git a/pages/zh_CN/docs/associations.md b/pages/zh_CN/docs/associations.md index c846ca42e3e..d4092be4f0d 100644 --- a/pages/zh_CN/docs/associations.md +++ b/pages/zh_CN/docs/associations.md @@ -208,59 +208,59 @@ db.Model(&users).Association("Team").Append(&userA, &userB, &[]User{userA, userB db.Model(&users).Association("Team").Replace(&userA, &userB, &[]User{userA, userB, userC}) ``` -## Delete Association Record +## 删除关联记录 -By default, `Replace`/`Delete`/`Clear` in `gorm.Association` only delete the reference, that is, set old associations's foreign key to null. +默认情况下, ` gorm.Association 中的 Replace `/` Delete `/` Clear ` 操作只会删除关联引用,也就是将旧的关联的外键设置为null。 -You can delete those objects with `Unscoped` (it has nothing to do with `ManyToMany`). +您可以使用 `Unscoped` 来删除这些对象(与 `ManyToMany` 无关)。 -How to delete is decided by `gorm.DB`. +删除操作由 `gorm.DB` 决定。 ```go -// Soft delete +// 软删除 // UPDATE `languages` SET `deleted_at`= ... db.Model(&user).Association("Languages").Unscoped().Clear() -// Delete permanently +// 永久删除 // DELETE FROM `languages` WHERE ... db.Unscoped().Model(&item).Association("Languages").Unscoped().Clear() ``` -## Delete with Select +## 使用选择删除 -You are allowed to delete selected has one/has many/many2many relations with `Select` when deleting records, for example: +您可以在删除记录时通过 `Select` 来删除具有 has one、has many、many2many 关系的记录,例如: ```go -// delete user's account when deleting user +// 删除 user 时,也删除 user 的 account db.Select("Account").Delete(&user) -// delete user's Orders, CreditCards relations when deleting user +// 删除 user 时,也删除 user 的 Orders、CreditCards 记录 db.Select("Orders", "CreditCards").Delete(&user) -// delete user's has one/many/many2many relations when deleting user +// 删除 user 时,也删除用户所有 has one/many、many2many 记录 db.Select(clause.Associations).Delete(&user) -// delete each user's account when deleting users +// 删除 users 时,也删除每一个 user 的 account db.Select("Account").Delete(&users) ``` {% note warn %} -**NOTE:** Associations will only be deleted if the deleting records's primary key is not zero, GORM will use those primary keys as conditions to delete selected associations +**注意:**只有在待删除记录的主键不为零时,关联关系才会被删除。GORM会将这些主键作为条件来删除选定的关联关系。 ```go -// DOESN'T WORK +// 不会起作用 db.Select("Account").Where("name = ?", "jinzhu").Delete(&User{}) -// will delete all user with name `jinzhu`, but those user's account won't be deleted +// 会删除所有 name=`jinzhu` 的 user,但这些 user 的 account 不会被删除 db.Select("Account").Where("name = ?", "jinzhu").Delete(&User{ID: 1}) -// will delete the user with name = `jinzhu` and id = `1`, and user `1`'s account will be deleted +// 会删除 name = `jinzhu` 且 id = `1` 的 user,并且 user `1` 的 account 也会被删除 db.Select("Account").Delete(&User{ID: 1}) -// will delete the user with id = `1`, and user `1`'s account will be deleted +// 会删除 id = `1` 的 user,并且 user `1` 的 account 也会被删除 ``` {% endnote %} -## Association Tags +## 关联标签(Association Tags) | 标签 | 描述 | | ---------------- | ----------------------------- | diff --git a/pages/zh_CN/docs/conventions.md b/pages/zh_CN/docs/conventions.md index a3eae53891a..3ac23178d99 100644 --- a/pages/zh_CN/docs/conventions.md +++ b/pages/zh_CN/docs/conventions.md @@ -150,7 +150,7 @@ user2 := User{Name: "jinzhu", UpdatedAt: time.Now()} db.Create(&user2) // 创建记录时,user2 的 `UpdatedAt` 不会被修改 user3 := User{Name: "jinzhu", UpdatedAt: time.Now()} -db.Save(&user3) // 更新世,user3 的 `UpdatedAt` 会修改为当前时间 +db.Save(&user3) // 更新时,user3 的 `UpdatedAt` 会修改为当前时间 ``` 你可以通过将 `autoUpdateTime` 标签置为 `false` 来禁用时间戳追踪,例如: diff --git a/pages/zh_CN/docs/create.md b/pages/zh_CN/docs/create.md index 3583456f4ee..d8d5e3d4bf9 100644 --- a/pages/zh_CN/docs/create.md +++ b/pages/zh_CN/docs/create.md @@ -22,22 +22,26 @@ users := []*User{ User{Name: "Jackson", Age: 19, Birthday: time.Now()}, } -result := db.Create(users) // pass a slice to insert multiple row +result := db.Create(users) // 传递切片以插入多行数据 -result.Error // returns error -result.RowsAffected // returns inserted records count +result.Error // 返回 error +result.RowsAffected // 返回插入记录的条数 ``` +{% note warn %} +**NOTE** 你无法向 'create' 传递结构体,所以你应该传入数据的指针. +{% endnote %} + ## 用指定的字段创建记录 -创建记录并为指定的字段分配值: +创建记录并为指定字段赋值。 ```go db.Select("Name", "Age", "CreatedAt").Create(&user) // INSERT INTO `users` (`name`,`age`,`created_at`) VALUES ("jinzhu", 18, "2020-07-04 11:05:21.775") ``` -创建记录并忽略要省略的传递字段的值: +创建记录并忽略传递给 'Omit' 的字段值 ```go db.Omit("Name", "Age", "CreatedAt").Create(&user) @@ -46,7 +50,7 @@ db.Omit("Name", "Age", "CreatedAt").Create(&user) ## 批量插入 -To efficiently insert large number of records, pass a slice to the `Create` method. GORM will generate a single SQL statement to insert all the data and backfill primary key values, hook methods will be invoked too. It will begin a **transaction** when records can be splited into multiple batches. +要高效地插入大量记录,请将切片传递给`Create`方法。 GORM will generate a single SQL statement to insert all the data and backfill primary key values, hook methods will be invoked too. It will begin a **transaction** when records can be splited into multiple batches. ```go var users = []User{{Name: "jinzhu1"}, {Name: "jinzhu2"}, {Name: "jinzhu3"}} diff --git a/pages/zh_CN/docs/dbresolver.md b/pages/zh_CN/docs/dbresolver.md index 08cd6d55b5b..88e19142a83 100644 --- a/pages/zh_CN/docs/dbresolver.md +++ b/pages/zh_CN/docs/dbresolver.md @@ -33,7 +33,7 @@ db.Use(dbresolver.Register(dbresolver.Config{ // sources/replicas load balancing policy Policy: dbresolver.RandomPolicy{}, // print sources/replicas mode in logger - ResolverModeReplica: true, + TraceResolverMode: true, }).Register(dbresolver.Config{ // use `db1` as sources (DB's default connection), `db5` as replicas for `User`, `Address` Replicas: []gorm.Dialector{mysql.Open("db5_dsn")}, diff --git a/pages/zh_CN/docs/error_handling.md b/pages/zh_CN/docs/error_handling.md index b9a613049b7..a87180366d1 100644 --- a/pages/zh_CN/docs/error_handling.md +++ b/pages/zh_CN/docs/error_handling.md @@ -36,9 +36,9 @@ if result := db.Where("name = ?", "jinzhu").First(&user); result.Error != nil { err := db.First(&user, 100).Error errors.Is(err, gorm.ErrRecordNotFound) ``` -## Dialect Translated Errors +## 翻译方言错误 -If you would like to be able to use the dialect translated errors(like ErrDuplicatedKey), then enable the TranslateError flag when opening a db connection. +如果您希望将数据库的方言错误转换为gorm的错误类型(例如将MySQL中的“Duplicate entry”转换为ErrDuplicatedKey),则在打开数据库连接时启用TranslateError标志。 ```go db, err := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{TranslateError: true}) diff --git a/pages/zh_CN/docs/migration.md b/pages/zh_CN/docs/migration.md index a286af4b31a..0ee2873f6ae 100644 --- a/pages/zh_CN/docs/migration.md +++ b/pages/zh_CN/docs/migration.md @@ -265,9 +265,26 @@ db.Migrator().RenameIndex(&User{}, "idx_name", "idx_name_2") GORM creates constraints when auto migrating or creating table, see [Constraints](constraints.html) or [Database Indexes](indexes.html) for details -## 其他迁移工具 +## Atlas Integration -GORM's AutoMigrate works well for most cases, but if you are looking for more serious migration tools, GORM provides a generic DB interface that might be helpful for you. +[Atlas](https://atlasgo.io) is an open-source database migration tool that has an official integration with GORM. + +While GORM's `AutoMigrate` feature works in most cases, at some point you many need to switch to a [versioned migrations](https://atlasgo.io/concepts/declarative-vs-versioned#versioned-migrations) strategy. + +Once this happens, the responsibility for planning migration scripts and making sure they are in line with what GORM expects at runtime is moved to developers. + +Atlas can automatically plan database schema migrations for developers using the official [GORM Provider](https://github.com/ariga/atlas-provider-gorm). After configuring the provider you can automatically plan migrations by running: +```bash +atlas migrate diff --env gorm +``` + +To learn how to use Atlas with GORM, check out the [official documentation](https://atlasgo.io/guides/orms/gorm). + + + +## Other Migration Tools + +To use GORM with other Go-based migration tools, GORM provides a generic DB interface that might be helpful for you. ```go // returns `*sql.DB` diff --git a/pages/zh_CN/docs/query.md b/pages/zh_CN/docs/query.md index b734575b9ea..8a4bf2b49b5 100644 --- a/pages/zh_CN/docs/query.md +++ b/pages/zh_CN/docs/query.md @@ -36,7 +36,7 @@ errors.Is(result.Error, gorm.ErrRecordNotFound) 对单个对象使用`Find`而不带limit,`db.Find(&user)`将会查询整个表并且只返回第一个对象,这是性能不高并且不确定的。 {% 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: +`First` and `Last` 方法会按主键排序找到第一条记录和最后一条记录 (分别)。 只有在目标 struct 是指针或者通过 `db.Model()` 指定 model 时,该方法才有效。 此外,如果相关 model 没有定义主键,那么将按 model 的第一个字段进行排序。 例如: ```go var user User @@ -70,7 +70,7 @@ db.First(&Language{}) ### 根据主键检索 -Objects can be retrieved using primary key by using [Inline Conditions](#inline_conditions) if the primary key is a number. When working with strings, extra care needs to be taken to avoid SQL Injection; check out [Security](security.html) section for details. +如果主键是数字类型,您可以使用 [内联条件](#inline_conditions) 来检索对象。 当使用字符串时,需要额外的注意来避免SQL注入;查看 [Security](security.html) 部分来了解详情。 ```go db.First(&user, 10) @@ -83,7 +83,7 @@ db.Find(&users, []int{1,2,3}) // SELECT * FROM users WHERE id IN (1,2,3); ``` -If the primary key is a string (for example, like a uuid), the query will be written as follows: +如果主键是字符串(例如像uuid),查询将被写成如下: ```go db.First(&user, "id = ?", "1b74413f-f3b8-409f-ac47-e8c062e3472a") @@ -103,7 +103,7 @@ db.Model(User{ID: 10}).First(&result) ``` {% note warn %} -**NOTE:** If you use gorm's specific field types like `gorm.DeletedAt`, it will run a different query for retrieving object/s. +**NOTE:** 如果您使用 gorm 的特定字段类型(例如 `gorm.DeletedAt`),它将运行不同的查询来检索对象。 {% endnote %} ```go type User struct { @@ -162,13 +162,13 @@ db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users) ``` {% note warn %} -If the object's primary key has been set, then condition query wouldn't cover the value of primary key but use it as a 'and' condition. For example: +如果对象设置了主键,条件查询将不会覆盖主键的值,而是用 And 连接条件。 例如: ```go var user = User{ID: 10} db.Where("id = ?", 20).First(&user) // SELECT * FROM users WHERE id = 10 and id = 20 ORDER BY id ASC LIMIT 1 ``` -This query would give `record not found` Error. So set the primary key attribute such as `id` to nil before you want to use the variable such as `user` to get new value from database. +这个查询将会给出`record not found`错误 所以,在你想要使用例如 `user` 这样的变量从数据库中获取新值前,需要将例如 `id` 这样的主键设置为nil。 {% endnote %} diff --git a/pages/zh_CN/gen/database_to_structs.md b/pages/zh_CN/gen/database_to_structs.md index 056affbc607..87f6d987375 100644 --- a/pages/zh_CN/gen/database_to_structs.md +++ b/pages/zh_CN/gen/database_to_structs.md @@ -247,3 +247,49 @@ WithOpts(opts ...ModelOpt) g.WithDataTypeMap(dataMap) ``` +## Generate From Sql + +Gen supports generate structs from sql following GORM conventions, it can be used like: + +```go +package main + +import ( + "gorm.io/gorm" + "gorm.io/rawsql" +) + +func main() { + g := gen.NewGenerator(gen.Config{ + OutPath: "../query", + Mode: gen.WithoutContext|gen.WithDefaultQuery|gen.WithQueryInterface, // generate mode + }) + // https://github.com/go-gorm/rawsql/blob/master/tests/gen_test.go + gormdb, _ := gorm.Open(rawsql.New(rawsql.Config{ + //SQL: rawsql, //create table sql + FilePath: []string{ + //"./sql/user.sql", // create table sql file + "./test_sql", // create table sql file directory + }, + })) + g.UseDB(gormdb) // reuse your gorm db + + // Generate basic type-safe DAO API for struct `model.User` following conventions + + g.ApplyBasic( + // Generate struct `User` based on table `users` + g.GenerateModel("users"), + + // Generate struct `Employee` based on table `users` + g.GenerateModelAs("users", "Employee"), + + ) +g.ApplyBasic( +// Generate structs from all tables of current database +g.GenerateAllTable()..., +) + // Generate the code + g.Execute() +} + +``` diff --git a/pages/zh_CN/gen/query.md b/pages/zh_CN/gen/query.md index eb43c94c241..a3e6c931afb 100644 --- a/pages/zh_CN/gen/query.md +++ b/pages/zh_CN/gen/query.md @@ -477,7 +477,7 @@ db.Table("(?) as u, (?) as p", subQuery1, subQuery2).Find(&User{}) ``` ### FirstOrInit -Initialize struct with more attributes if record not found, those `Attrs` won't be used to build the SQL query +如果没有找到记录,可以使用包含更多的属性的结构体初始化 user,`Attrs` 不会被用于生成查询 SQL ```go // User not found, initialize it with given conditions and Attrs @@ -496,7 +496,7 @@ u.WithContext(ctx).Attrs(field.Attrs(&model.User{Age: 20})).Where(u.Name.Eq("gen // user -> User{ID: 111, Name: "gen", Age: 18} ``` -`Assign` attributes to struct regardless it is found or not, those attributes won't be used to build SQL query and the final data won't be saved into database +不管是否找到记录,`Assign` 都会将属性赋值给 struct,但这些属性不会被用于生成查询 SQL,也不会被保存到数据库 ```go // User not found, initialize it with give conditions and Assign attributes @@ -505,23 +505,24 @@ u.WithContext(ctx).Assign(field.Attrs(map[string]interface{}{"age": 20})).Where( // Found user with `name` = `gen`, update it with Assign attributes u.WithContext(ctx).Assign(field.Attrs(&model.User{Name: "gen_assign"}).Select(dal.User.ALL)).Where(u.Name.Eq("gen")).FirstOrInit() + // SELECT * FROM USERS WHERE name = gen' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "gen", Age: 20} ``` ### FirstOrCreate -Get first matched record or create a new one with given conditions (only works with struct, map conditions), `RowsAffected` returns created/updated record's count +获取匹配的第一条记录或者根据给定条件创建一条新纪录(仅 struct, map 条件有效),`RowsAffected` 返回创建、更新的记录数 ```go -// Found user with `name` = `gen` -result := u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate(&user) -// user -> User{ID: 111, Name: "gen", "Age": 18} +//通过`name` = `gen`查找用户 +result:=u.WithContext(ctx).Where(u.Name.Eq(jinzhu)).FirstOrCreate() +// 用户信息 -> User{ID: 111, Name: "gen", "Age": 18} // result.RowsAffected // => 0 ``` -Create struct with more attributes if record not found, those `Attrs` won't be used to build SQL query +如果没有找到记录,可以使用包含更多的属性的结构体创建记录,`Attrs` 不会被用于生成查询 SQL 。 ```go // User not found, create it with give conditions and Attrs @@ -536,7 +537,7 @@ u.WithContext(ctx).Attrs(field.Attrs(&model.User{Age: 20})).Where(u.Name.Eq("gen // user -> User{ID: 111, Name: "gen", Age: 18} ``` -`Assign` attributes to the record regardless it is found or not and save them back to the database. +不管是否找到记录,`Assign` 都会将属性赋值给 struct,并将结果写回数据库 ```go // User not found, initialize it with give conditions and Assign attributes @@ -558,6 +559,7 @@ u.WithContext(ctx).Assign(u.Age.Value(20)).Where(u.Name.Eq("gen")).FirstOrCreate // user -> User{ID: 111, Name: "gen", Age: 20} ``` + ### Struct & Map Conditions ```go @@ -572,7 +574,7 @@ u.WithContext(ctx).Where(field.Attrs(map[string]interface{}{"name": "gen", "age" ``` {% note warn %} -**NOTE** When querying with struct, GORM GEN will only query with non-zero fields, that means if your field's value is `0`, `''`, `false` or other [zero values](https://tour.golang.org/basics/12), it won't be used to build query conditions, for example: +**注意** 当使用 struct 进行查询时,GORM GEN只会使用非零值字段进行查询。这意味着如果您的字段值为 `0`、`''`、`false` 或其他 [零值](https://tour.golang.org/basics/12),该字段不会被用于构建查询条件,例如: {% endnote %} ```go @@ -580,18 +582,18 @@ u.WithContext(ctx).Where(field.Attrs(&User{Name: "gen", Age: 0})).Find() // SELECT * FROM users WHERE name = "gen"; ``` -To include zero values in the query conditions, you can use a map, which will include all key-values as query conditions, for example: +如果想要在查询条件中包含零值,你可以使用 map ,其会包含所有的键值对查询条件,例如: ```go u.WithContext(ctx).Where(field.Attrs(map[string]interface{}{"name": "gen", "age": 0})).Find() // SELECT * FROM users WHERE name = "gen" AND age = 0; ``` -For more details, see [Specify Struct search fields](#specify_search_fields). +了解更多的细节,请阅读 [Specify Struct search fields](#specify_search_fields) 。 ### Specify Struct search fields -When searching with struct, you can specify which particular values from the struct to use in the query conditions by passing in the relevant the dbname to `Attrs()`, for example: +当使用 struct 进行查询时,你可以通过向 `Select()` 、`Omit()` 传入 字段名来指定查询条件,例如: ```go u.WithContext(ctx).Where(field.Attrs(&User{Name: "gen"}).Select(u.Name,u.Age)).Find() diff --git a/pages/zh_CN/gen/rawsql_driver.html b/pages/zh_CN/gen/rawsql_driver.html index f66bc540bcb..1a2a0d75540 100644 --- a/pages/zh_CN/gen/rawsql_driver.html +++ b/pages/zh_CN/gen/rawsql_driver.html @@ -3,8 +3,8 @@ - - + + Gorm @@ -13,4 +13,3 @@ https://github.com/go-gorm/gen - diff --git a/pages/zh_CN/rawsql.html b/pages/zh_CN/rawsql.html new file mode 100644 index 00000000000..580e7b8b21f --- /dev/null +++ b/pages/zh_CN/rawsql.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql + + diff --git a/pages/zh_CN/rawsql_driver.html b/pages/zh_CN/rawsql_driver.html new file mode 100644 index 00000000000..650146900a8 --- /dev/null +++ b/pages/zh_CN/rawsql_driver.html @@ -0,0 +1,15 @@ + + + + + + + + Gorm + + + + https://gorm.io
+ https://github.com/go-gorm/rawsql_driver + + diff --git a/themes/navy/languages/fr_FR.yml b/themes/navy/languages/fr_FR.yml index cc5fc588cbd..f56bd7fbb8d 100644 --- a/themes/navy/languages/fr_FR.yml +++ b/themes/navy/languages/fr_FR.yml @@ -9,27 +9,27 @@ menu: contribute: Contribute search: Search documents... index: - get_started: Get started + get_started: Commencer page: - contents: Contents - back_to_top: Back to Top - improve: Improve this page - prev: Prev - next: Next - last_updated: "Last updated: %s" + contents: Contenus + back_to_top: Retour en haut de la page + improve: Améliorer ce document + prev: Précédent + next: Suivant + last_updated: "Dernière mise à jour : %s" sidebar: docs: - getting_started: Getting Started - overview: Overview + getting_started: Premiers pas + overview: Aperçu declaring_models: Declaring Models conventions: Conventions connecting_to_the_database: Connecting to Database crud_interface: CRUD Interface - create: Create - query: Query + create: Créer + query: Requête advanced_query: Advanced Query - update: Update - delete: Delete + update: Mettre à jour + delete: Supprimer raw_sql_and_builder: Raw SQL & SQL Builder batch: Batch Processing associations: Associations @@ -53,7 +53,7 @@ sidebar: data_types: Customize Data Types scopes: Scopes settings: Settings - advanced_topics: Advanced Topics + advanced_topics: Sujets avancés dbresolver: Database Resolver serializer: Serializer sharding: Sharding @@ -68,13 +68,13 @@ sidebar: write_driver: Write Driver change_log: ChangeLog community: Community - contribute: Contribute - translate: Translate current site + contribute: Contribuer + translate: Traduire dans l'onglet actuel gen: - getting_started: Getting Started - overview: Overview + getting_started: Premiers pas + overview: Aperçu dao: DAO - create: Create + create: Créer query: Query update: Update delete: Delete @@ -83,7 +83,7 @@ sidebar: annotation: Annotation database_to_structs: Database To Structs gentool: Gen Tool - tutorials: Tutorials - gorm_clause: GORM Clause + tutorials: Tutoriels + gorm_clause: Clause GORM transaction: Transaction - plugins: GORM Plugins + plugins: Plugins GORM