查询

  1. var user User
  2. var users []User
  3. // 根据主键查询第一条记录
  4. db.First(&user)
  5. //// SELECT * FROM users ORDER BY id LIMIT 1;
  6. // 随机获取一条记录
  7. db.Take(&user)
  8. //// SELECT * FROM users LIMIT 1;
  9. // 根据主键查询最后一条记录
  10. db.Last(&user)
  11. //// SELECT * FROM users ORDER BY id DESC LIMIT 1;
  12. // 查询所有的记录
  13. db.Find(&users)
  14. //// SELECT * FROM users;
  15. // 查询指定的某条记录(仅当主键为整型时可用)
  16. db.First(&user, 10)
  17. //// 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. // <>
  8. db.Where("name <> ?", "jinzhu").Find(&users)
  9. //// SELECT * FROM users WHERE name <> 'jinzhu';
  10. // IN
  11. db.Where("name IN (?)", []string{"jinzhu", "jinzhu 2"}).Find(&users)
  12. //// SELECT * FROM users WHERE name in ('jinzhu','jinzhu 2');
  13. // LIKE
  14. db.Where("name LIKE ?", "%jin%").Find(&users)
  15. //// SELECT * FROM users WHERE name LIKE '%jin%';
  16. // AND
  17. db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users)
  18. //// SELECT * FROM users WHERE name = 'jinzhu' AND age >= 22;
  19. // Time
  20. db.Where("updated_at > ?", lastWeek).Find(&users)
  21. //// SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00';
  22. // BETWEEN
  23. db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
  24. //// 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";

你可以使用指针或实现 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. }

Not 条件