1. type User struct {
  2. gorm.Model
  3. Name string
  4. Age int
  5. Birthday time.Time
  6. }

1 添加

(1) db.Create()

  • 使用NewRecord()查询主键是否存在
  • 主键为空使用Create()创建记录 ```go // 添加单个记录 user := User{Name: “Jinzhu”, Age: 18, Birthday: time.Now()} db.Create(&user)

// 添加多条记录 var users = []User{ {Name: “jinzhu1”, Birthday: time.Now()}, {Name: “jinzhu2”, Birthday: time.Now()}, {Name: “jinzhu3”, Birthday: time.Now()}, } db.Create(&users)

  1. <a name="tmdmS"></a>
  2. ## (2) 根据Map创建
  3. ```go
  4. db.Model(&User{}).Create(map[string]interface{}{
  5. "Name": "jinzhu", "Age": 18,
  6. })
  7. // batch insert from `[]map[string]interface{}{}`
  8. db.Model(&User{}).Create([]map[string]interface{}{
  9. {"Name": "jinzhu_1", "Age": 18},
  10. {"Name": "jinzhu_2", "Age": 20},
  11. })

(3) 默认值

您可以通过标签 default 为字段定义默认值,如:

  1. type User struct {
  2. ID int64
  3. Name string `gorm:"default:galeone"`
  4. Age int64 `gorm:"default:18"`
  5. }

插入记录到数据库时,默认值 会被用于 填充值为 零值 的字段

注意 对于声明了默认值的字段,像 0、’’、false 等零值是不会保存到数据库。您需要使用指针类型或 Scanner/Valuer 来避免这个问题,例如:

  1. type User struct {
  2. gorm.Model
  3. Name string
  4. Age *int `gorm:"default:18"`
  5. Active sql.NullBool `gorm:"default:true"`
  6. }
  1. user := User{Age: new(int), Age: 18))}
  2. db.Create(&user)
  1. user := User{Active: sql.NullBool{"", true}, Age:18}
  2. db.Create(&user)

2 查询

(1) 查询单个记录

  1. // 根据主键查询第一条记录
  2. db.First(&user) // SELECT * FROM users ORDER BY id LIMIT 1;
  3. // 根据主键查询最后一条记录
  4. db.Last(&user) // SELECT * FROM users ORDER BY id DESC LIMIT 1;
  5. // 查询指定的某条记录(仅当主键为整型时可用)
  6. db.First(&user, 10) // SELECT * FROM users WHERE id = 10;
  7. // Get first matched record
  8. db.Where("name = ?", "jinzhu").First(&user)
  9. // SELECT * FROM users WHERE name = 'jinzhu' limit 1;

(2) 检索多个记录

  1. // 查询所有的记录
  2. db.Find(&users) // SELECT * FROM users;
  3. // Get all matched records
  4. db.Where("name = ?", "jinzhu").Find(&users)
  5. // SELECT * FROM users WHERE name = 'jinzhu';
  6. // <>
  7. db.Where("name <> ?", "jinzhu").Find(&users)
  8. // SELECT * FROM users WHERE name <> 'jinzhu';
  9. // IN
  10. db.Where("name IN (?)", []string{"jinzhu", "jinzhu 2"}).Find(&users)
  11. // SELECT * FROM users WHERE name in ('jinzhu','jinzhu 2');
  12. // LIKE
  13. db.Where("name LIKE ?", "%jin%").Find(&users)
  14. // SELECT * FROM users WHERE name LIKE '%jin%';
  15. // AND
  16. db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users)
  17. // SELECT * FROM users WHERE name = 'jinzhu' AND age >= 22;
  18. // Time
  19. db.Where("updated_at > ?", lastWeek).Find(&users)
  20. // SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00';
  21. // BETWEEN
  22. db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
  23. // SELECT * FROM users WHERE created_at BETWEEN '2000-01-01 00:00:00' AND '2000-01-08 00:00:00';

(3) Struct & Map查询

  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. // 主键的切片
  8. db.Where([]int64{20, 21, 22}).Find(&users)
  9. // SELECT * FROM users WHERE id IN (20, 21, 22);

提示:当通过Struct进行查询时,GORM将会只通过非零值字段查询,这意味着如果你的字段值为0,’’,false或者其他零值时,将不会被用于构建查询条件,例如:

  1. db.Where(&User{Name: "jinzhu", Age: 0}).Find(&users)
  2. // SELECT * FROM users WHERE name = "jinzhu";

你可以使用指针或实现 Scanner/Valuer 接口来避免这个问题.

  1. // 使用指针
  2. type User struct {
  3. gorm.Model
  4. Name string
  5. Age *int
  6. }
  7. // 使用 Scanner/Valuer
  8. type User struct {
  9. gorm.Model
  10. Name string
  11. Age sql.NullInt64 // sql.NullInt64 实现了 Scanner/Valuer 接口
  12. }

(4) 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";

(5) 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)
  8. // SELECT * FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2';

(6) 内联条件

作用与Where查询类似,当内联条件与多个立即执行方法一起使用时, 内联条件不会传递给后面的立即执行方法。

  1. // 根据主键获取记录 (只适用于整形主键)
  2. db.First(&user, 23)
  3. // SELECT * FROM users WHERE id = 23 LIMIT 1;
  4. // 根据主键获取记录, 如果它是一个非整形主键
  5. db.First(&user, "id = ?", "string_primary_key")
  6. // SELECT * FROM users WHERE id = 'string_primary_key' LIMIT 1;
  7. // Plain SQL
  8. db.Find(&user, "name = ?", "jinzhu")
  9. // SELECT * FROM users WHERE name = "jinzhu";
  10. db.Find(&users, "name <> ? AND age > ?", "jinzhu", 20)
  11. // SELECT * FROM users WHERE name <> "jinzhu" AND age > 20;
  12. // Struct
  13. db.Find(&users, User{Age: 20})
  14. // SELECT * FROM users WHERE age = 20;
  15. // Map
  16. db.Find(&users, map[string]interface{}{"age": 20})
  17. // SELECT * FROM users WHERE age = 20;

(7) 额外查询选项

  1. // 为查询 SQL 添加额外的 SQL 操作
  2. db.Set("gorm:query_option", "FOR UPDATE").First(&user, 10)
  3. // SELECT * FROM users WHERE id = 10 FOR UPDATE;

(8) FirstOrInit

获取匹配的第一条记录,否则根据给定的条件初始化一个新的对象 (仅支持 struct 和 map 条件)

  1. // 未找到
  2. db.FirstOrInit(&user, User{Name: "non_existing"})
  3. // user -> User{Name: "non_existing"}
  4. // 找到
  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}

1) Attrs

如果记录未找到,将使用参数初始化 struct.

  1. // 未找到
  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. // 找到
  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}

2) Assign

不管记录是否找到,都将参数赋值给 struct.

  1. // 未找到
  2. db.Where(User{Name: "non_existing"}).Assign(User{Age: 20}).FirstOrInit(&user)
  3. // user -> User{Name: "non_existing", Age: 20}
  4. // 找到
  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}

(9) FirstOrCreate

获取匹配的第一条记录, 否则根据给定的条件创建一个新的记录 (仅支持 struct 和 map 条件)

  1. // 未找到
  2. db.FirstOrCreate(&user, User{Name: "non_existing"})
  3. // INSERT INTO "users" (name) VALUES ("non_existing");
  4. // user -> User{Id: 112, Name: "non_existing"}
  5. // 找到
  6. db.Where(User{Name: "Jinzhu"}).FirstOrCreate(&user)
  7. // user -> User{Id: 111, Name: "Jinzhu"}

(10) 高级查询

1) SubQuery

  1. db.Where("amount > ?", db.Table("orders").Select("AVG(amount)").Where("state = ?", "paid").SubQuery()).Find(&orders)
  2. // SELECT * FROM "orders" WHERE "orders"."deleted_at" IS NULL AND (amount > (SELECT AVG(amount) FROM "orders" WHERE (state = 'paid')));

2) select

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;

3) order

Order,指定从数据库中检索出记录的顺序。

  1. // 多字段排序
  2. db.Order("age desc, name").Find(&users) // 法一
  3. db.Order("age desc").Order("name").Find(&users) // 法二
  4. // SELECT * FROM users ORDER BY age desc, name;

4) limit

Limit,指定从数据库检索出的最大记录数。

  1. db.Limit(3).Find(&users)
  2. // SELECT * FROM users LIMIT 3;

5) offset

Offset,指定开始返回记录前要跳过的记录数。

  1. db.Offset(3).Find(&users)

6) count

  1. db.Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Find(&users).Count(&count)
  2. // SELECT count(*) FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (count)

7) 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. // 使用Scan将多条结果扫描进事先准备好的结构体切片中
  6. type Result struct {
  7. Date time.Time
  8. Total int
  9. }
  10. var rets []Result
  11. db.Table("users").Select("date(created_at) as date, sum(age) as total").Group("date(created_at)").Scan(&rets)
  12. rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Rows()
  13. for rows.Next() {
  14. ...
  15. }
  16. type Result struct {
  17. Date time.Time
  18. Total int64
  19. }
  20. db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Scan(&results)

8) 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")
  8. .Joins("JOIN credit_cards ON credit_cards.user_id = users.id")
  9. .Where("credit_cards.number = ?", "411111111111").Find(&user)

9) Pluck

Pluck,查询 model 中的一个列作为切片

  1. var ages []int64
  2. db.Find(&users).Pluck("age", &ages)
  3. var names []string
  4. db.Model(&User).Pluck("name", &names)

10) Scan

Scan,查询 model 中的多个列作为切片

  1. type Result struct {
  2. Name string
  3. Age int
  4. }
  5. var result Result
  6. db.Table("users").Select("name, age").Where("name = ?", "Antonio").Scan(&result)

(11) 链式操作

在调用立即执行方法前不会生成Query语句,借助这个特性你可以创建一个函数来处理一些通用逻辑。
Method Chaining,Gorm 实现了链式操作接口,所以你可以把代码写成这样:

  1. // 创建一个查询
  2. tx := db.Where("name = ?", "jinzhu")
  3. // 添加更多条件
  4. if someCondition {
  5. tx = tx.Where("age = ?", 20)
  6. } else {
  7. tx = tx.Where("age = ?", 30)
  8. }
  9. if yetAnotherCondition {
  10. tx = tx.Where("active = ?", 1)
  11. }

(12) 立即执行方法

Immediate methods ,立即执行方法是指那些会立即生成SQL语句并发送到数据库的方法, 他们一般是CRUD方法,比如:Create, First, Find, Take, Save, UpdateXXX, Delete, Scan, Row, Rows…
这有一个基于上面链式方法代码的立即执行方法的例子:

  1. tx.Find(&user) // SELECT * FROM users where name = 'jinzhu' AND age = 30 AND active = 1;

3 更新

  1. // 法一
  2. db.First(&user)
  3. user.Name = "七米"
  4. user.Age = 99
  5. db.Save(&user)
  6. // 法二
  7. db.Model(&user).Update("name", "hello")
  8. // 法三
  9. db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "active": false})

4 删除

警告: 删除记录时,请确保主键字段有值,GORM 会通过主键去删除记录,如果主键为空,GORM 会删除该 model 的所有记录。

  1. // 删除一条现有记录
  2. db.Delete(&email)
  3. // 删除全部匹配的记录
  4. db.Where("email LIKE ?", "%jinzhu%").Delete(Email{})
  5. db.Delete(Email{}, "email LIKE ?", "%jinzhu%")
  6. // 软删除, 如果一个 model 有 DeletedAt 字段,他将自动获得软删除的功能
  7. // 当调用 Delete 方法时, 只会将DeletedAt 字段的值会被设置为当前时间
  8. // 查询记录时会忽略被软删除的记录
  9. db.Where("age = 20").Find(&user)
  10. // SELECT * FROM users WHERE age = 20 AND deleted_at IS NULL;
  11. // Unscoped 方法可以查询被软删除的记录
  12. db.Unscoped().Where("age = 20").Find(&users)
  13. // SELECT * FROM users WHERE age = 20;
  14. // 物理删除
  15. db.Unscoped().Delete(&order)

5 原生SQL

  1. db.Raw("SELECT name, age FROM users WHERE name = ?", "Antonio")