检索单个对象

GORM 提供 First, Take, Last 方法,以便从数据库中检索单个对象。当查询数据库时它添加了 LIMIT 1 条件。当没有找到记录时,它会返回错误 ErrRecordNotFound

  1. // 获取第一条记录(主键升序)
  2. db.First(&user)
  3. // SELECT * FROM users ORDER BY id LIMIT 1;
  4. // 获取一条记录,没有指定排序字段
  5. db.Take(&user)
  6. // SELECT * FROM users LIMIT 1;
  7. // 获取最后一条记录(主键降序)
  8. db.Last(&user)
  9. // SELECT * FROM users ORDER BY id DESC LIMIT 1;
  10. result := db.First(&user)
  11. result.RowsAffected // 返回找到的记录数
  12. result.Error // returns error
  13. // 检查 ErrRecordNotFound 错误
  14. errors.Is(result.Error, gorm.ErrRecordNotFound)

检索对象

  1. // 获取全部记录
  2. result := db.Find(&users)
  3. // SELECT * FROM users;
  4. result.RowsAffected // 返回找到的记录数,相当于 `len(users)`
  5. result.Error // returns error

条件

String 条件

  1. // 获取第一条匹配的记录
  2. db.Where("name = ?", "jinzhu").First(&user)
  3. // SELECT * FROM users WHERE name = 'jinzhu' ORDER BY id LIMIT 1;
  4. // 获取全部匹配的记录
  5. db.Where("name <> ?", "jinzhu").Find(&users)
  6. // SELECT * FROM users WHERE name <> 'jinzhu';
  7. // IN
  8. db.Where("name IN ?", []string{"jinzhu", "jinzhu 2"}).Find(&users)
  9. // SELECT * FROM users WHERE name in ('jinzhu','jinzhu 2');
  10. // LIKE
  11. db.Where("name LIKE ?", "%jin%").Find(&users)
  12. // SELECT * FROM users WHERE name LIKE '%jin%';
  13. // AND
  14. db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users)
  15. // SELECT * FROM users WHERE name = 'jinzhu' AND age >= 22;
  16. // Time
  17. db.Where("updated_at > ?", lastWeek).Find(&users)
  18. // SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00';
  19. // BETWEEN
  20. db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
  21. // SELECT * FROM users WHERE created_at BETWEEN '2000-01-01 00:00:00' AND '2000-01-08 00:00:00';

Struct & Map 条件

  1. // Struct
  2. db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
  3. // SELECT * FROM users WHERE name = "jinzhu" AND age = 20 ORDER BY id 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);

注意 当使用结构作为条件查询时,GORM 只会查询非零值字段。这意味着如果您的字段值为 0''false 或其他 零值,该字段不会被用于构建查询条件,例如:

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

您可以使用 map 来构建查询条件,例如:

  1. db.Where(map[string]interface{}{"Name": "jinzhu", "Age": 0}).Find(&users)
  2. // SELECT * FROM users WHERE name = "jinzhu" AND age = 0;

内联条件

用法与 Where 类似

  1. // 根据主键获取记录(仅适用于整型主键)
  2. db.First(&user, 23)
  3. // SELECT * FROM users WHERE id = 23;
  4. // 根据主键获取记录,如果是非整型主键
  5. db.First(&user, "id = ?", "string_primary_key")
  6. // SELECT * FROM users WHERE id = 'string_primary_key';
  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;

Not 条件

构建 NOT 条件,用法与 Where 类似

  1. db.Not("name = ?", "jinzhu").First(&user)
  2. // SELECT * FROM users WHERE NOT name = "jinzhu" ORDER BY id LIMIT 1;
  3. // Not In
  4. db.Not(map[string]interface{}{"name": []string{"jinzhu", "jinzhu 2"}}).Find(&users)
  5. // SELECT * FROM users WHERE name NOT IN ("jinzhu", "jinzhu 2");
  6. // Struct
  7. db.Not(User{Name: "jinzhu", Age: 18}).First(&user)
  8. // SELECT * FROM users WHERE name <> "jinzhu" AND age <> 18 ORDER BY id LIMIT 1;
  9. // 不在主键切片中的记录
  10. db.Not([]int64{1,2,3}).First(&user)
  11. // SELECT * FROM users WHERE id NOT IN (1,2,3) ORDER BY id LIMIT 1;

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", Age: 18}).Find(&users)
  5. // SELECT * FROM users WHERE name = 'jinzhu' OR (name = 'jinzhu 2' AND age = 18);
  6. // Map
  7. db.Where("name = 'jinzhu'").Or(map[string]interface{}{"name": "jinzhu 2", "age": 18}).Find(&users)
  8. // SELECT * FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2';

您还可以在高级查询中查看 Group 条件,更轻松地编写复杂 SQL

选择特定字段

选择您想从数据库中检索的字段,默认情况下会选择全部字段

  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

指定从数据库检索记录时的排序方式

  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;

Limit & Offset

Limit 指定获取记录的最大数量 Offset 指定在开始返回记录之前要跳过的记录数量

  1. db.Limit(3).Find(&users)
  2. // SELECT * FROM users LIMIT 3;
  3. // 通过 -1 消除 Limit 条件
  4. db.Limit(10).Find(&users1).Limit(-1).Find(&users2)
  5. // SELECT * FROM users LIMIT 10; (users1)
  6. // SELECT * FROM users; (users2)
  7. db.Offset(3).Find(&users)
  8. // SELECT * FROM users OFFSET 3;
  9. db.Limit(10).Offset(5).Find(&users)
  10. // SELECT * FROM users OFFSET 5 LIMIT 10;
  11. // 通过 -1 消除 Offset 条件
  12. db.Offset(10).Find(&users1).Offset(-1).Find(&users2)
  13. // SELECT * FROM users OFFSET 10; (users1)
  14. // SELECT * FROM users; (users2)

Group & Having

  1. type result struct {
  2. Date time.Time
  3. Total int
  4. }
  5. db.Model(&User{}).Select("name, sum(age) as total").Where("name LIKE ?", "group%").Group("name").First(&result)
  6. // SELECT name, sum(age) as total FROM `users` WHERE name LIKE "group%" GROUP BY `name`
  7. db.Model(&User{}).Select("name, sum(age) as total").Group("name").Having("name = ?", "group").Find(&result)
  8. // SELECT name, sum(age) as total FROM `users` GROUP BY `name` HAVING name = "group"
  9. rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Rows()
  10. for rows.Next() {
  11. ...
  12. }
  13. rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Rows()
  14. for rows.Next() {
  15. ...
  16. }
  17. type Result struct {
  18. Date time.Time
  19. Total int64
  20. }
  21. db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Scan(&results)

Distinct

从模型中选择不相同的值

  1. db.Distinct("name", "age").Order("name, age desc").Find(&results)

Distinct 也可以配合 Pluck, Count 使用

Joins

指定 Joins 条件

  1. type result struct {
  2. Name string
  3. Email string
  4. }
  5. db.Model(&User{}).Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Scan(&result{})
  6. // SELECT users.name, emails.email FROM `users` left join emails on emails.user_id = users.id
  7. rows, err := db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Rows()
  8. for rows.Next() {
  9. ...
  10. }
  11. db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Scan(&results)
  12. // 带参数的多表连接
  13. 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)

Joins 预加载

您可以使用 Joins 实现单条 SQL 预加载关联记录,例如:

  1. db.Joins("Company").Find(&users)
  2. // SELECT `users`.`id`,`users`.`name`,`users`.`age`,`Company`.`id` AS `Company__id`,`Company`.`name` AS `Company__name` FROM `users` LEFT JOIN `companies` AS `Company` ON `users`.`company_id` = `Company`.`id`;

参考 预加载 了解详情

Scan

Scan 结果至 struct,用法与 Find 类似

  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)
  7. // 原生 SQL
  8. db.Raw("SELECT name, age FROM users WHERE name = ?", "Antonio").Scan(&result)