//可以直接书写聚合语句 //等价于: SELECT count(*) as total FROM `foods` total := []int{}
//Model函数,用于指定绑定的模型,这里生成了一个Food{}变量。目的是从模型变量里面提取表名,Pluck函数我们没有直接传递绑定表名的结构体变量,gorm库不知道表名是什么,所以这里需要指定表名 //Pluck函数,主要用于查询一列值 db.Model(&Food{}).Select("count(*) as total").Pluck("total", &total)
fmt.Println(total[0])
order
1 2
//等价于: SELECT * FROM `foods` WHERE (create_time >= '2018-11-06 00:00:00') ORDER BY create_time desc db.Where("create_time >= ?", "2018-11-06 00:00:00").Order("create_time desc").Find(&foods)
limit / offset
1 2
//等价于: SELECT * FROM `foods` ORDER BY create_time desc LIMIT 10 OFFSET 0 db.Order("create_time desc").Limit(10).Offset(0).Find(&foods)
count
1 2 3 4 5
var total int64 = 0 //等价于: SELECT count(*) FROM `foods` //这里也需要通过model设置模型,让gorm可以提取模型对应的表名 db.Model(Food{}).Count(&total) fmt.Println(total)
group by ( 通常结合 自己新定义一个结构体+scan() )
1 2 3 4 5 6 7 8 9 10 11 12 13
/统计每个商品分类下面有多少个商品 //定一个Result结构体类型,用来保存查询结果 type Result struct { Type int Total int }
var results []Result //等价于: SELECT type, count(*) as total FROM `foods` GROUP BY type HAVING (total > 0) db.Model(Food{}).Select("type, count(*) as total").Group("type").Having("total > 0").Scan(&results)
sql := "SELECT type, count(*) as total FROM `foods` where create_time > ? GROUP BY type HAVING (total > 0)" //因为sql语句使用了一个问号(?)作为绑定参数, 所以需要传递一个绑定参数(Raw第二个参数). //Raw函数支持绑定多个参数 db.Raw(sql, "2018-11-06 00:00:00").Scan(&results) //依旧scan
更新数据
save 先拿出来,改字段,再塞回去
1 2 3 4 5 6 7 8
//等价于: SELECT * FROM `foods` WHERE (id = '2') LIMIT 1 db.Where("id = ?", 2).Take(&food)
type Profile struct { gorm.Model Name string UserID uint// 外键存储在 Profile 表 User User `gorm:"foreignKey:UserID"`// Profile 属于 User ,且必须含有此属性(grom会默认使用User 的id字段) }
Has One
拥有,和属于不同的是,has one是父表拥有子表,但也可以不拥有,因为这时候父表也是有意义的
1 2 3 4 5 6 7 8 9 10 11
type User struct { gorm.Model Name string Profile Profile `gorm:"foreignKey:UserID"`// User 拥有一个 Profile }
type Profile struct { gorm.Model Name string UserID uint// 外键仍然在 Profile 表,但关系方向不同 }
总结
无论是 belongs to 还是 has one,外键都在子表
belongs to 子表含有父表结构体 ,has one 父表含有子表结构体
tag是打在结构体上的
使用场景:当表a可以包含表b,且b不一定要有一个a的时候,可以用has one,如果b必须关联a,那就要用belongs to
关联外键
什么时候需要自定义外键?
当想用非ID字段(如 UUID、Email、Refer)作为关联依据时。
当数据库设计不允许使用默认外键命名时。
当需要更灵活的关联逻辑时
1 2 3 4 5 6 7 8 9 10 11 12 13
//belongs to type User struct { gorm.Model Refer string// 自定义关联外键 Name string }
type Profile struct { gorm.Model Name string User User `gorm:"foreignKey:UserRefer;references:Refer"`// 使用 Refer 作为关联外键 UserRefer string// 外键字段 }
1 2 3 4 5 6 7 8 9 10 11 12 13
//has one type User struct { gorm.Model Refer string// 自定义关联外键 Name string Profile Profile `gorm:"foreignKey:UserRefer;references:Refer"`// 使用 Refer 作为关联外键 }
type Profile struct { gorm.Model Name string UserRefer string// 外键字段 }