Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Group/Order分组与排序

Group方法用于查询分组,Order方法用于查询排序。使用示例:

Code Block
languagego
// 获取默认配置的数据库对象(配置名称为"default")
db := g.DB()

// SELECT COUNT(*) total,age FROM `user` GROUP BY age
db.Model("user").Fields("COUNT(*) total,age").Group("age").All()

// SELECT * FROM `student` ORDER BY class asc,course asc,score desc
db.Model("student").Order("class asc,course asc,score desc").All()

同时,goframeORM提供了一些常用的排序方法:

Code Block
languagego
// 按照指定字段递增排序
func (m *Model) OrderAsc(column string) *Model
// 按照指定字段递减排序
func (m *Model) OrderDesc(column string) *Model
// 随机排序
func (m *Model) OrderRandom() *Model

使用示例:

Code Block
languagego
// SELECT `id`,`title` FROM `article` ORDER BY `created_at` ASC
db.Model("article").Fields("id,title").OrderAsc("created_at").All()

// SELECT `id`,`title` FROM `article` ORDER BY `views` DESC
db.Model("article").Fields("id,title").OrderDesc("views").All()

// SELECT `id`,`title` FROM `article` ORDER BY RAND()
db.Model("article").Fields("id,title").OrderRandom().All()

Having条件过滤

Having方法用于查询结果的条件过滤。使用示例:

Code Block
languagego
// SELECT COUNT(*) total,age FROM `user` GROUP BY age HAVING total>100
db.Model("user").Fields("COUNT(*) total,age").Group("age").Having("total>100").All()

// SELECT * FROM `student` ORDER BY class HAVING score>60
db.Model("student").Order("class").Having("score>?", 60).All()















Panel
titleContent Menu

Table of Contents