创建
- 创建记录:
user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()}
db.NewRecord(user) // => 主键为空返回`true`
db.Create(&user) db.NewRecord(user) // => 创建`user`后返回`false`
- 设置默认值: 设可以在gorm tag中定义默认值,然后插入SQL将忽略具有默认值的这些字段,并且其值为空,并且在将记录插入数据库 后,gorm将从数据库加载这些字段的值。
type Animal struct {
ID int64 Name
string `gorm:"default:'galeone'"`
Age int64 }
var animal = Animal{Age: 99, Name: ""}
db.Create(&animal) INSERT INTO animals("age") values('99');
SELECT name from animals WHERE ID=111; // 返回主键为 111 animal.Name => 'galeone'
查询
- 获取:第一条记录 获 / 最后一条记录 最 / 所有记录
// 获取第一条记录,按主键排序 db.First(&user)
SELECT * FROM users ORDER BY id LIMIT 1;
// 获取最后一条记录,按主键排序 db.Last(&user)
SELECT * FROM users ORDER BY id DESC LIMIT 1;
// 获取所有记录 db.Find(&users)
SELECT * FROM users;
// 使用主键获取记录 db.First(&user, 10)
SELECT * FROM users WHERE id = 10;
- Where查询条件
// 获取第一个匹配记录 db.Where("name = ?", "jinzhu").First(&user)
SELECT * FROM users WHERE name = 'jinzhu' limit 1;
// 获取所有匹配记录 db.Where("name = ?", "jinzhu").Find(&users)
SELECT * FROM users WHERE name = 'jinzhu';
// IN db.Where("name in (?)", []string{"jinzhu", "jinzhu 2"}).Find(&users)
// LIKE db.Where("name LIKE ?", "%jin%").Find(&users) // AND db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users) 注意:当使用struct查询时,GORM将只查询那些具有值的字段
// Struct db.Where(&User{Name: "zhangyang", Age: 20}).First(&user)
SELECT * FROM users WHERE name = "zhangyang" AND age = 20 LIMIT 1;
// Map db.Where(map[string]interface{}{"name": "zhangyang", "age": 20}).Find(&users)
SELECT * FROM users WHERE name = "zhangyang" AND age = 20;
// 主键的Slice db.Where([]int64{20, 21, 22}).Find(&users)
SELECT * FROM users WHERE id IN (20, 21, 22);
- Not条件查询
db.Not("name", "jinzhu").First(&user)
SELECT * FROM users WHERE name "jinzhu" LIMIT 1;
// Not In db.Not("name", []string{"jinzhu", "jinzhu 2"}).Find(&users)
SELECT * FROM users WHERE name NOT IN ("jinzhu", "jinzhu 2");
// Not In slice of primary keys db.Not([]int64{1,2,3}).First(&user)
SELECT * FROM users WHERE id NOT IN (1,2,3); db.Not([]int64{}).First(&user)
SELECT * FROM users;
- Or条件查询
db.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&users) SELECT * FROM users WHERE role = 'admin' OR role = 'super_admin'; // Struct db.Where("name = 'jinzhu'").Or(User{Name: "jinzhu 2"}).Find(&users) SELECT * FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2';
- Select 指定要从数据库检索的字段 指 ,默认情况下,将选择所有字段 默 ;
db.Select("name, age").Find(&users)
SELECT name, age FROM users; db.Select([]string{"name", "age"}).Find(&users)
SELECT name, age FROM users;
- Order
db.Order("age desc, name").Find(&users) SELECT * FROM users ORDER BY age desc, name; // Multiple orders db.Order("age desc").Order("name").Find(&users) SELECT * FROM users ORDER BY age desc, name; // ReOrder 从数据库检索记录时指定顺序,将重排序设置为true以覆盖定义的条件 db.Order("age desc").Find(&users1).Order("age", true).Find(&users2) SELECT * FROM users ORDER BY age desc; (users1) SELECT * FROM users ORDER BY age; (users2)
- Limit , Offset 指定要检索的记录数
db.Limit(3).Find(&users) SELECT * FROM users LIMIT 3; 指定在开始返回记录之前要跳过跳 的记录数 db.Offset(3).Find(&users) SELECT * FROM users OFFSET 3; // Cancel offset condition with -1 db.Offset(10).Find(&users1).Offset(-1).Find(&users2) SELECT * FROM users OFFSET 10; (users1) SELECT * FROM users; (users2)
- Count,Group & Having,Join
获取记录数 db.Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Find(&users).Count(&count) SELECT * from USERS WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (users) SELECT count(*) FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (count) db.Model(&User{}).Where("name = ?", "jinzhu").Count(&count) SELECT count(*) FROM users WHERE name = 'jinzhu'; (count) //指定表deleted_users db.Table("deleted_users").Count(&count) //rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Rows() rows, err := db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Rows()
更新
- 更新全部字段 更Save将包括执行更新SQL时的所有字段,即使它没有更改
db.First(&user) user.Name = "jinzhu 2" user.Age = 100 db.Save(&user)
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
// 更新单个属性(如果更改) db.Model(&user).Update("name", "hello")
UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111;
// 使用组合条件更新单个属性 db.Model(&user).Where("active = ?", true).Update("name", "hello")
UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111 AND active=true;
// 使用`map`更新多个属性,只会更新这些更改的字段 db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false})
UPDATE users SET name='hello', age=18, actived=false, updated_at='2013-11-17 21:34:10' WHERE id=111;
// 使用`struct`更新多个属性,只会更新这些更改的和非空白字段 db.Model(&user).Updates(User{Name: "hello", Age: 18})
UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 21:34:10' WHERE id = 111;
// 警告:当使用struct更新时,FORM将仅更新具有非空值的字段
// 对于下面的更新,什么都不会更新为"",0,false是其类型的空白值 db.Model(&user).Updates(User{Name: "", Age: 0, Actived: false}) 更新选择的字段 更如果您只想在更新时更新或忽略某些字段,可以使用Select, Omit db.Model(&user).Select("name").Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false})
UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111; db.Model(&user).Omit("name").Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false})
UPDATE users SET age=18, actived=false, updated_at='2013-11-17 21:34:10' WHERE id=111;
删除
- 警告:删除记录时,需要确保其主要字段具有值, 警 GORM将使用主键删除记录,如果主要字段为空, 将 GORM将删除模型的所 将 有记录
// 删除存在的记录 db.Delete(&email) DELETE from emails where id=10;
// 为Delete语句添加额外的SQL选项 db.Set("gorm:delete_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Delete(&email)
DELETE from emails where id=10 OPTION (OPTIMIZE FOR UNKNOWN); 批量删除 批删除所有匹配记录 db.Where("email LIKE ?", "%jinzhu%").Delete(Email{})
DELETE from emails where email LIKE "%jinhu%"; db.Delete(Email{}, "email LIKE ?", "%jinzhu%")
DELETE from emails where email LIKE "%jinhu%";