type User struct { ID uint Name string Email *string Age uint8 Birthday *time.Time MemberNumber sql.NullString ActivatedAt sql.NullTime CreatedAt time.Time UpdatedAt time.Time }
权限控制
设置字段的权限位只读、只写、只创建、只更新或者被忽略
1 2 3 4 5 6 7 8 9 10 11 12
type User struct { Name string`gorm:"<-:create"`// 允许读和创建 Name string`gorm:"<-:update"`// 允许读和更新 Name string`gorm:"<-"`// 允许读和写(创建和更新) Name string`gorm:"<-:false"`// 允许读,禁止写 Name string`gorm:"->"`// 只读(除非有自定义配置,否则禁止写) Name string`gorm:"->;<-:create"`// 允许读和写 Name string`gorm:"->:false;<-:create"`// 仅创建(禁止从 db 读) Name string`gorm:"-"`// 通过 struct 读写会忽略该字段 Name string`gorm:"-:all"`// 通过 struct 读写、迁移会忽略该字段 Name string`gorm:"-:migration"`// 通过 struct 迁移会忽略该字段 }
db.First(&user, 10) // SELECT * FROM users WHERE id = 10;
db.First(&user, "10") // SELECT * FROM users WHERE id = 10;
db.Find(&users, []int{1,2,3}) // SELECT * FROM users WHERE id IN (1,2,3);
条件查询
字符串条件
1 2 3 4 5 6 7 8 9
// 获取匹配的记录 db.Where("name = ?", "jinzhu").Find(&user) // IN db.Where("name IN ?", []string{"jinzhu", "jinzhu 2"}).Find(&user) // LIKE db.Where("name LIKE ?", "%jinzhu%").Find(&users) // AND // Time // BETWEEN