当前位置: 首页 > 文档资料 > GORM 1.0 中文文档 >

4. CRUD:读写数据

优质
小牛编辑
132浏览
2023-12-01

创建 {#c}

创建记录

  1. user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()}
  2. db.NewRecord(user) // => 主键为空返回`true`
  3. db.Create(&user)
  4. db.NewRecord(user) // => 创建`user`后返回`false`

默认值

您可以在gorm tag中定义默认值,然后插入SQL将忽略具有默认值的这些字段,并且其值为空,并且在将记录插入数据库后,gorm将从数据库加载这些字段的值。

  1. type Animal struct {
  2. ID int64
  3. Name string `gorm:"default:'galeone'"`
  4. Age int64
  5. }
  6. var animal = Animal{Age: 99, Name: ""}
  7. db.Create(&animal)
  8. // INSERT INTO animals("age") values('99');
  9. // SELECT name from animals WHERE ID=111; // 返回主键为 111
  10. // animal.Name => 'galeone'

在Callbacks中设置主键

如果要在BeforeCreate回调中设置主字段的值,可以使用scope.SetColumn,例如:

  1. func (user *User) BeforeCreate(scope *gorm.Scope) error {
  2. scope.SetColumn("ID", uuid.New())
  3. return nil
  4. }

扩展创建选项

  1. // 为Instert语句添加扩展SQL选项
  2. db.Set("gorm:insert_option", "ON CONFLICT").Create(&product)
  3. // INSERT INTO products (name, code) VALUES (NULL, "code") ON CONFLICT;

查询 {#q}

  1. // 获取第一条记录,按主键排序
  2. db.First(&user)
  3. //// SELECT * FROM users ORDER BY id LIMIT 1;
  4. // 获取最后一条记录,按主键排序
  5. db.Last(&user)
  6. //// SELECT * FROM users ORDER BY id DESC LIMIT 1;
  7. // 获取所有记录
  8. db.Find(&users)
  9. //// SELECT * FROM users;
  10. // 使用主键获取记录
  11. db.First(&user, 10)
  12. //// SELECT * FROM users WHERE id = 10;

Where查询条件 (简单SQL)

  1. // 获取第一个匹配记录
  2. db.Where("name = ?", "jinzhu").First(&user)
  3. //// SELECT * FROM users WHERE name = 'jinzhu' limit 1;
  4. // 获取所有匹配记录
  5. db.Where("name = ?", "jinzhu").Find(&users)
  6. //// SELECT * FROM users WHERE name = 'jinzhu';
  7. db.Where("name <> ?", "jinzhu").Find(&users)
  8. // IN
  9. db.Where("name in (?)", []string{"jinzhu", "jinzhu 2"}).Find(&users)
  10. // LIKE
  11. db.Where("name LIKE ?", "%jin%").Find(&users)
  12. // AND
  13. db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users)
  14. // Time
  15. db.Where("updated_at > ?", lastWeek).Find(&users)
  16. db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)

Where查询条件 (Struct & Map)

注意:当使用struct查询时,GORM将只查询那些具有值的字段

  1. // Struct
  2. db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
  3. //// SELECT * FROM users WHERE name = "jinzhu" AND age = 20 LIMIT 1;
  4. // Map
  5. db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users)
  6. //// SELECT * FROM users WHERE name = "jinzhu" AND age = 20;
  7. // 主键的Slice
  8. db.Where([]int64{20, 21, 22}).Find(&users)
  9. //// SELECT * FROM users WHERE id IN (20, 21, 22);

Not条件查询

  1. db.Not("name", "jinzhu").First(&user)
  2. //// SELECT * FROM users WHERE name <> "jinzhu" LIMIT 1;
  3. // Not In
  4. db.Not("name", []string{"jinzhu", "jinzhu 2"}).Find(&users)
  5. //// SELECT * FROM users WHERE name NOT IN ("jinzhu", "jinzhu 2");
  6. // Not In slice of primary keys
  7. db.Not([]int64{1,2,3}).First(&user)
  8. //// SELECT * FROM users WHERE id NOT IN (1,2,3);
  9. db.Not([]int64{}).First(&user)
  10. //// SELECT * FROM users;
  11. // Plain SQL
  12. db.Not("name = ?", "jinzhu").First(&user)
  13. //// SELECT * FROM users WHERE NOT(name = "jinzhu");
  14. // Struct
  15. db.Not(User{Name: "jinzhu"}).First(&user)
  16. //// SELECT * FROM users WHERE name <> "jinzhu";

带内联条件的查询

注意:使用主键查询时,应仔细检查所传递的值是否为有效主键,以避免SQL注入

  1. // 按主键获取
  2. db.First(&user, 23)
  3. //// SELECT * FROM users WHERE id = 23 LIMIT 1;
  4. // 简单SQL
  5. db.Find(&user, "name = ?", "jinzhu")
  6. //// SELECT * FROM users WHERE name = "jinzhu";
  7. db.Find(&users, "name <> ? AND age > ?", "jinzhu", 20)
  8. //// SELECT * FROM users WHERE name <> "jinzhu" AND age > 20;
  9. // Struct
  10. db.Find(&users, User{Age: 20})
  11. //// SELECT * FROM users WHERE age = 20;
  12. // Map
  13. db.Find(&users, map[string]interface{}{"age": 20})
  14. //// SELECT * FROM users WHERE age = 20;

Or条件查询

  1. db.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&users)
  2. //// SELECT * FROM users WHERE role = 'admin' OR role = 'super_admin';
  3. // Struct
  4. db.Where("name = 'jinzhu'").Or(User{Name: "jinzhu 2"}).Find(&users)
  5. //// SELECT * FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2';
  6. // Map
  7. db.Where("name = 'jinzhu'").Or(map[string]interface{}{"name": "jinzhu 2"}).Find(&users)

查询链

Gorm有一个可链接的API,你可以这样使用它

  1. db.Where("name <> ?","jinzhu").Where("age >= ? and role <> ?",20,"admin").Find(&users)
  2. //// SELECT * FROM users WHERE name <> 'jinzhu' AND age >= 20 AND role <> 'admin';
  3. db.Where("role = ?", "admin").Or("role = ?", "super_admin").Not("name = ?", "jinzhu").Find(&users)

扩展查询选项

  1. // 为Select语句添加扩展SQL选项
  2. db.Set("gorm:query_option", "FOR UPDATE").First(&user, 10)
  3. //// SELECT * FROM users WHERE id = 10 FOR UPDATE;

FirstOrInit

获取第一个匹配的记录,或者使用给定的条件初始化一个新的记录(仅适用于struct,map条件)

  1. // Unfound
  2. db.FirstOrInit(&user, User{Name: "non_existing"})
  3. //// user -> User{Name: "non_existing"}
  4. // Found
  5. db.Where(User{Name: "Jinzhu"}).FirstOrInit(&user)
  6. //// user -> User{Id: 111, Name: "Jinzhu", Age: 20}
  7. db.FirstOrInit(&user, map[string]interface{}{"name": "jinzhu"})
  8. //// user -> User{Id: 111, Name: "Jinzhu", Age: 20}

Attrs

如果未找到记录,则使用参数初始化结构

  1. // Unfound
  2. db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrInit(&user)
  3. //// SELECT * FROM USERS WHERE name = 'non_existing';
  4. //// user -> User{Name: "non_existing", Age: 20}
  5. db.Where(User{Name: "non_existing"}).Attrs("age", 20).FirstOrInit(&user)
  6. //// SELECT * FROM USERS WHERE name = 'non_existing';
  7. //// user -> User{Name: "non_existing", Age: 20}
  8. // Found
  9. db.Where(User{Name: "Jinzhu"}).Attrs(User{Age: 30}).FirstOrInit(&user)
  10. //// SELECT * FROM USERS WHERE name = jinzhu';
  11. //// user -> User{Id: 111, Name: "Jinzhu", Age: 20}

Assign

将参数分配给结果,不管它是否被找到

  1. // Unfound
  2. db.Where(User{Name: "non_existing"}).Assign(User{Age: 20}).FirstOrInit(&user)
  3. //// user -> User{Name: "non_existing", Age: 20}
  4. // Found
  5. db.Where(User{Name: "Jinzhu"}).Assign(User{Age: 30}).FirstOrInit(&user)
  6. //// SELECT * FROM USERS WHERE name = jinzhu';
  7. //// user -> User{Id: 111, Name: "Jinzhu", Age: 30}

FirstOrCreate

获取第一个匹配的记录,或创建一个具有给定条件的新记录(仅适用于struct, map条件)

  1. // Unfound
  2. db.FirstOrCreate(&user, User{Name: "non_existing"})
  3. //// INSERT INTO "users" (name) VALUES (NULL, Name: "non_existing"}
  4. // Found
  5. db.Where(User{Name: "Jinzhu"}).FirstOrCreate(&user)
  6. //// user -> User{Id: 111, Name: "Jinzhu"}

Attrs

如果未找到记录,则为参数分配结构

  1. // Unfound
  2. db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrCreate(&user)
  3. //// SELECT * FROM users WHERE name = 'non_existing';
  4. //// INSERT INTO "users" (name, age) VALUES (NULL, 20);
  5. //// user -> User{Id: 112, Name: "non_existing", Age: 20}
  6. // Found
  7. db.Where(User{Name: "jinzhu"}).Attrs(User{Age: 30}).FirstOrCreate(&user)
  8. //// SELECT * FROM users WHERE name = 'jinzhu';
  9. //// user -> User{Id: 111, Name: "jinzhu", Age: 20}

Assign

将其分配给记录,而不管它是否被找到,并保存回数据库。

  1. // Unfound
  2. db.Where(User{Name: "non_existing"}).Assign(User{Age: 20}).FirstOrCreate(&user)
  3. //// SELECT * FROM users WHERE name = 'non_existing';
  4. //// INSERT INTO "users" (name, age) VALUES (NULL, 20);
  5. //// user -> User{Id: 112, Name: "non_existing", Age: 20}
  6. // Found
  7. db.Where(User{Name: "jinzhu"}).Assign(User{Age: 30}).FirstOrCreate(&user)
  8. //// SELECT * FROM users WHERE name = 'jinzhu';
  9. //// UPDATE users SET age=30 WHERE id = 111;
  10. //// user -> User{Id: 111, Name: "jinzhu", Age: 30}

Select

指定要从数据库检索的字段,默认情况下,将选择所有字段;

  1. db.Select("name, age").Find(&users)
  2. //// SELECT name, age FROM users;
  3. db.Select([]string{"name", "age"}).Find(&users)
  4. //// SELECT name, age FROM users;
  5. db.Table("users").Select("COALESCE(age,?)", 42).Rows()
  6. //// SELECT COALESCE(age,'42') FROM users;

Order

在从数据库检索记录时指定顺序,将重排序设置为true以覆盖定义的条件

  1. db.Order("age desc, name").Find(&users)
  2. //// SELECT * FROM users ORDER BY age desc, name;
  3. // Multiple orders
  4. db.Order("age desc").Order("name").Find(&users)
  5. //// SELECT * FROM users ORDER BY age desc, name;
  6. // ReOrder
  7. db.Order("age desc").Find(&users1).Order("age", true).Find(&users2)
  8. //// SELECT * FROM users ORDER BY age desc; (users1)
  9. //// SELECT * FROM users ORDER BY age; (users2)

Limit

指定要检索的记录数

  1. db.Limit(3).Find(&users)
  2. //// SELECT * FROM users LIMIT 3;
  3. // Cancel limit condition with -1
  4. db.Limit(10).Find(&users1).Limit(-1).Find(&users2)
  5. //// SELECT * FROM users LIMIT 10; (users1)
  6. //// SELECT * FROM users; (users2)

Offset

指定在开始返回记录之前要跳过的记录数

  1. db.Offset(3).Find(&users)
  2. //// SELECT * FROM users OFFSET 3;
  3. // Cancel offset condition with -1
  4. db.Offset(10).Find(&users1).Offset(-1).Find(&users2)
  5. //// SELECT * FROM users OFFSET 10; (users1)
  6. //// SELECT * FROM users; (users2)

Count

获取模型的记录数

  1. db.Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Find(&users).Count(&count)
  2. //// SELECT * from USERS WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (users)
  3. //// SELECT count(*) FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (count)
  4. db.Model(&User{}).Where("name = ?", "jinzhu").Count(&count)
  5. //// SELECT count(*) FROM users WHERE name = 'jinzhu'; (count)
  6. db.Table("deleted_users").Count(&count)
  7. //// SELECT count(*) FROM deleted_users;

Group & Having

  1. rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Rows()
  2. for rows.Next() {
  3. ...
  4. }
  5. rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Rows()
  6. for rows.Next() {
  7. ...
  8. }
  9. type Result struct {
  10. Date time.Time
  11. Total int64
  12. }
  13. db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Scan(&results)

Join

指定连接条件

  1. rows, err := db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Rows()
  2. for rows.Next() {
  3. ...
  4. }
  5. db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Scan(&results)
  6. // 多个连接与参数
  7. db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Joins("JOIN credit_cards ON credit_cards.user_id = users.id").Where("credit_cards.number = ?", "411111111111").Find(&user)

Pluck

将模型中的单个列作为地图查询,如果要查询多个列,可以使用Scan

  1. var ages []int64
  2. db.Find(&users).Pluck("age", &ages)
  3. var names []string
  4. db.Model(&User{}).Pluck("name", &names)
  5. db.Table("deleted_users").Pluck("name", &names)
  6. // 要返回多个列,做这样:
  7. db.Select("name, age").Find(&users)

Scan {#Scan}

将结果扫描到另一个结构中。

  1. type Result struct {
  2. Name string
  3. Age int
  4. }
  5. var result Result
  6. db.Table("users").Select("name, age").Where("name = ?", 3).Scan(&result)
  7. // Raw SQL
  8. db.Raw("SELECT name, age FROM users WHERE name = ?", 3).Scan(&result)

Scopes {#Scopes}

将当前数据库连接传递到func(*DB) *DB,可以用于动态添加条件

  1. func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
  2. return db.Where("amount > ?", 1000)
  3. }
  4. func PaidWithCreditCard(db *gorm.DB) *gorm.DB {
  5. return db.Where("pay_mode_sign = ?", "C")
  6. }
  7. func PaidWithCod(db *gorm.DB) *gorm.DB {
  8. return db.Where("pay_mode_sign = ?", "C")
  9. }
  10. func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
  11. return func (db *gorm.DB) *gorm.DB {
  12. return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
  13. }
  14. }
  15. db.Scopes(AmountGreaterThan1000, PaidWithCreditCard).Find(&orders)
  16. // 查找所有信用卡订单和金额大于1000
  17. db.Scopes(AmountGreaterThan1000, PaidWithCod).Find(&orders)
  18. // 查找所有COD订单和金额大于1000
  19. db.Scopes(OrderStatus([]string{"paid", "shipped"})).Find(&orders)
  20. // 查找所有付费,发货订单

指定表名

  1. // 使用User结构定义创建`deleted_users`表
  2. db.Table("deleted_users").CreateTable(&User{})
  3. var deleted_users []User
  4. db.Table("deleted_users").Find(&deleted_users)
  5. //// SELECT * FROM deleted_users;
  6. db.Table("deleted_users").Where("name = ?", "jinzhu").Delete()
  7. //// DELETE FROM deleted_users WHERE name = 'jinzhu';

预加载 {#p}

  1. db.Preload("Orders").Find(&users)
  2. //// SELECT * FROM users;
  3. //// SELECT * FROM orders WHERE user_id IN (1,2,3,4);
  4. db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
  5. //// SELECT * FROM users;
  6. //// SELECT * FROM orders WHERE user_id IN (1,2,3,4) AND state NOT IN ('cancelled');
  7. db.Where("state = ?", "active").Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)
  8. //// SELECT * FROM users WHERE state = 'active';
  9. //// SELECT * FROM orders WHERE user_id IN (1,2) AND state NOT IN ('cancelled');
  10. db.Preload("Orders").Preload("Profile").Preload("Role").Find(&users)
  11. //// SELECT * FROM users;
  12. //// SELECT * FROM orders WHERE user_id IN (1,2,3,4); // has many
  13. //// SELECT * FROM profiles WHERE user_id IN (1,2,3,4); // has one
  14. //// SELECT * FROM roles WHERE id IN (4,5,6); // belongs to

自定义预加载SQL

您可以通过传递func(db *gorm.DB) *gorm.DB(与Scopes的使用方法相同)来自定义预加载SQL,例如:

  1. db.Preload("Orders", func(db *gorm.DB) *gorm.DB {
  2. return db.Order("orders.amount DESC")
  3. }).Find(&users)
  4. //// SELECT * FROM users;
  5. //// SELECT * FROM orders WHERE user_id IN (1,2,3,4) order by orders.amount DESC;

嵌套预加载

  1. db.Preload("Orders.OrderItems").Find(&users)
  2. db.Preload("Orders", "state = ?", "paid").Preload("Orders.OrderItems").Find(&users)

更新 {#u}

更新全部字段

Save将包括执行更新SQL时的所有字段,即使它没有更改

  1. db.First(&user)
  2. user.Name = "jinzhu 2"
  3. user.Age = 100
  4. db.Save(&user)
  5. //// UPDATE users SET name='jinzhu 2', age=100, birthday='2016-01-01', updated_at = '2013-11-17 21:34:10' WHERE id=111;

更新更改字段

如果只想更新更改的字段,可以使用Update, Updates

  1. // 更新单个属性(如果更改)
  2. db.Model(&user).Update("name", "hello")
  3. //// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111;
  4. // 使用组合条件更新单个属性
  5. db.Model(&user).Where("active = ?", true).Update("name", "hello")
  6. //// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111 AND active=true;
  7. // 使用`map`更新多个属性,只会更新这些更改的字段
  8. db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false})
  9. //// UPDATE users SET name='hello', age=18, actived=false, updated_at='2013-11-17 21:34:10' WHERE id=111;
  10. // 使用`struct`更新多个属性,只会更新这些更改的和非空白字段
  11. db.Model(&user).Updates(User{Name: "hello", Age: 18})
  12. //// UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 21:34:10' WHERE id = 111;
  13. // 警告:当使用struct更新时,FORM将仅更新具有非空值的字段
  14. // 对于下面的更新,什幺都不会更新为"",0,false是其类型的空白值
  15. db.Model(&user).Updates(User{Name: "", Age: 0, Actived: false})

更新选择的字段

如果您只想在更新时更新或忽略某些字段,可以使用Select, Omit

  1. db.Model(&user).Select("name").Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false})
  2. //// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111;
  3. db.Model(&user).Omit("name").Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false})
  4. //// UPDATE users SET age=18, actived=false, updated_at='2013-11-17 21:34:10' WHERE id=111;

更新更改字段但不进行Callbacks

以上更新操作将执行模型的BeforeUpdate, AfterUpdate方法,更新其UpdatedAt时间戳,在更新时保存它的Associations,如果不想调用它们,可以使用UpdateColumn, UpdateColumns

  1. // 更新单个属性,类似于`Update`
  2. db.Model(&user).UpdateColumn("name", "hello")
  3. //// UPDATE users SET name='hello' WHERE id = 111;
  4. // 更新多个属性,与“更新”类似
  5. db.Model(&user).UpdateColumns(User{Name: "hello", Age: 18})
  6. //// UPDATE users SET name='hello', age=18 WHERE id = 111;

Batch Updates 批量更新

Callbacks在批量更新时不会运行

  1. db.Table("users").Where("id IN (?)", []int{10, 11}).Updates(map[string]interface{}{"name": "hello", "age": 18})
  2. //// UPDATE users SET name='hello', age=18 WHERE id IN (10, 11);
  3. // 使用struct更新仅适用于非零值,或使用map[string]interface{}
  4. db.Model(User{}).Updates(User{Name: "hello", Age: 18})
  5. //// UPDATE users SET name='hello', age=18;
  6. // 使用`RowsAffected`获取更新记录计数
  7. db.Model(User{}).Updates(User{Name: "hello", Age: 18}).RowsAffected

使用SQL表达式更新

  1. DB.Model(&product).Update("price", gorm.Expr("price * ? + ?", 2, 100))
  2. //// UPDATE "products" SET "price" = price * '2' + '100', "updated_at" = '2013-11-17 21:34:10' WHERE "id" = '2';
  3. DB.Model(&product).Updates(map[string]interface{}{"price": gorm.Expr("price * ? + ?", 2, 100)})
  4. //// UPDATE "products" SET "price" = price * '2' + '100', "updated_at" = '2013-11-17 21:34:10' WHERE "id" = '2';
  5. DB.Model(&product).UpdateColumn("quantity", gorm.Expr("quantity - ?", 1))
  6. //// UPDATE "products" SET "quantity" = quantity - 1 WHERE "id" = '2';
  7. DB.Model(&product).Where("quantity > 1").UpdateColumn("quantity", gorm.Expr("quantity - ?", 1))
  8. //// UPDATE "products" SET "quantity" = quantity - 1 WHERE "id" = '2' AND quantity > 1;

在Callbacks中更改更新值

如果要使用BeforeUpdate, BeforeSave更改回调中的更新值,可以使用scope.SetColumn,例如

  1. func (user *User) BeforeSave(scope *gorm.Scope) (err error) {
  2. if pw, err := bcrypt.GenerateFromPassword(user.Password, 0); err == nil {
  3. scope.SetColumn("EncryptedPassword", pw)
  4. }
  5. }

额外更新选项

  1. // 为Update语句添加额外的SQL选项
  2. db.Model(&user).Set("gorm:update_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Update("name, "hello")
  3. //// UPDATE users SET name='hello', updated_at = '2013-11-17 21:34:10' WHERE id=111 OPTION (OPTIMIZE FOR UNKNOWN);

删除/软删除 {#d}

警告 删除记录时,需要确保其主要字段具有值,GORM将使用主键删除记录,如果主要字段为空,GORM将删除模型的所有记录

  1. // 删除存在的记录
  2. db.Delete(&email)
  3. //// DELETE from emails where id=10;
  4. // 为Delete语句添加额外的SQL选项
  5. db.Set("gorm:delete_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Delete(&email)
  6. //// DELETE from emails where id=10 OPTION (OPTIMIZE FOR UNKNOWN);

批量删除

删除所有匹配记录

  1. db.Where("email LIKE ?", "%jinzhu%").Delete(Email{})
  2. //// DELETE from emails where email LIKE "%jinhu%";
  3. db.Delete(Email{}, "email LIKE ?", "%jinzhu%")
  4. //// DELETE from emails where email LIKE "%jinhu%";

软删除

如果模型有DeletedAt字段,它将自动获得软删除功能! 那幺在调用Delete时不会从数据库中永久删除,而是只将字段DeletedAt的值设置为当前时间。

  1. db.Delete(&user)
  2. //// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE id = 111;
  3. // 批量删除
  4. db.Where("age = ?", 20).Delete(&User{})
  5. //// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE age = 20;
  6. // 软删除的记录将在查询时被忽略
  7. db.Where("age = 20").Find(&user)
  8. //// SELECT * FROM users WHERE age = 20 AND deleted_at IS NULL;
  9. // 使用Unscoped查找软删除的记录
  10. db.Unscoped().Where("age = 20").Find(&users)
  11. //// SELECT * FROM users WHERE age = 20;
  12. // 使用Unscoped永久删除记录
  13. db.Unscoped().Delete(&order)
  14. //// DELETE FROM orders WHERE id=10;

关联 {#a}

默认情况下,当创建/更新记录时,GORM将保存其关联,如果关联具有主键,GORM将调用Update来保存它,否则将被创建。

  1. user := User{
  2. Name: "jinzhu",
  3. BillingAddress: Address{Address1: "Billing Address - Address 1"},
  4. ShippingAddress: Address{Address1: "Shipping Address - Address 1"},
  5. Emails: []Email{
  6. {Email: "jinzhu@example.com"},
  7. {Email: "jinzhu-2@example@example.com"},
  8. },
  9. Languages: []Language{
  10. {Name: "ZH"},
  11. {Name: "EN"},
  12. },
  13. }
  14. db.Create(&user)
  15. //// BEGIN TRANSACTION;
  16. //// INSERT INTO "addresses" (address1) VALUES (NULL,billing_address_id,shipping_address_id) VALUES (NULL, 1, 2);
  17. //// INSERT INTO "emails" (user_id,email) VALUES (NULL, "jinzhu@example.com");
  18. //// INSERT INTO "emails" (user_id,email) VALUES (NULL, "jinzhu-2@example.com");
  19. //// INSERT INTO "languages" ("name") VALUES (NULL,"language_id") VALUES (NULL, 1);
  20. //// INSERT INTO "languages" ("name") VALUES (NULL,"language_id") VALUES (NULL, 2);
  21. //// COMMIT;
  22. db.Save(&user)

参考Associations更多详细信息

创建/更新时跳过保存关联

默认情况下保存记录时,GORM也会保存它的关联,你可以通过设置gorm:save_associationsfalse跳过它。

  1. db.Set("gorm:save_associations", false).Create(&user)
  2. db.Set("gorm:save_associations", false).Save(&user)

tag设置跳过保存关联

您可以使用tag来配置您的struct,以便在创建/更新时不会保存关联

  1. type User struct {
  2. gorm.Model
  3. Name string
  4. CompanyID uint
  5. Company Company `gorm:"save_associations:false"`
  6. }
  7. type Company struct {
  8. gorm.Model
  9. Name string
  10. }