// gorm.Model 的定义 type Model struct { ID uint`gorm:"primaryKey"` CreatedAt time.Time UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` }
1 2 3 4 5 6 7 8 9 10 11 12
type User struct { gorm.Model Name string Age sql.NullInt64 Birthday *time.Time Email string`gorm:"type:varchar(100);unique_index"` Role string`gorm:"size:255"`// 设置字段大小为255 MemberNumber *string`gorm:"unique;not null"`// 设置会员号(member number)唯一并且不为空 Num int`gorm:"AUTO_INCREMENT"`// 设置 num 为自增类型 Address string`gorm:"index:addr"`// 给address字段创建名为addr的索引 IgnoreMe int`gorm:"-"`// 忽略本字段 }
嵌入结构体
1 2 3 4 5 6 7 8 9 10 11 12
type User struct { gorm.Model Name string } // 等效于 type User struct { ID uint`gorm:"primaryKey"` CreatedAt time.Time UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` Name string }
字段标签
声明 model 时,tag 是可选的,GORM 支持以下 tag: tag 名大小写不敏感,但建议使用 camelCase 风格
// Get first matched record db.Where("name = ?", "jinzhu").First(&user) // SELECT * FROM users WHERE name = 'jinzhu' ORDER BY id LIMIT 1;
// Get all matched records db.Where("name <> ?", "jinzhu").Find(&users) // SELECT * FROM users WHERE name <> 'jinzhu';
// IN db.Where("name IN ?", []string{"jinzhu", "jinzhu 2"}).Find(&users) // SELECT * FROM users WHERE name IN ('jinzhu','jinzhu 2');
// LIKE db.Where("name LIKE ?", "%jin%").Find(&users) // SELECT * FROM users WHERE name LIKE '%jin%';
// AND db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users) // SELECT * FROM users WHERE name = 'jinzhu' AND age >= 22;
// Time db.Where("updated_at > ?", lastWeek).Find(&users) // SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00';
// BETWEEN db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users) // SELECT * FROM users WHERE created_at BETWEEN '2000-01-01 00:00:00' AND '2000-01-08 00:00:00'
更新
保存所有字段
1 2 3 4 5 6
// 保存所有字段 var u UserInfo db.First(&u) u.Name = "jpc" db.Save(&u) // UPDATE user_info SET name='jpc' WHERE id=1
更新单个列
1 2 3 4
// 更新单个列 db.Model(&UserInfo{}).Where("name = ?", "jpc").Update("name", "贾小白") // UPDATE user_info SET name='贾小白' WHERE active='jpc';
更新多列
1 2 3
// 更新多个列 db.Model(&UserInfo{}).Where("name = ?", "贾小白").Updates(map[string]interface{}{"name": "jpc", "hobby": "羽毛球"}) // UPDATE user_info SET name='jpc', hobby='羽毛球' WHERE name="贾小白"
删除
根据主键删除
1 2 3 4 5 6 7 8 9
db.Delete(&User{}, 10) // DELETE FROM users WHERE id = 10;
db.Delete(&User{}, "10") // DELETE FROM users WHERE id = 10;
db.Delete(&users, []int{1,2,3}) // DELETE FROM users WHERE id IN (1,2,3);