func (ps postSlice) orderedBy(key string, desc bool) { var ms multiSorter byPoints := func(p1, p2 *Post) bool { return p1.Points < p2.Points } byPosted := func(p1, p2 *Post) bool { return p2.PostAt.After(p1.PostAt) } switch key { case "points": ms = multiSorter{less: []lessFunc{byPoints}} case "post_at": ms = multiSorter{less: []lessFunc{byPosted}} default: glog.Warn("orderedBy: posts sort by key %s not implement yet.\n", key) return } ms.posts = ps if desc { sort.Sort(sort.Reverse(&ms)) } else { sort.Sort(&ms) } }
// taxonomy func getTopicsByTaxonomy(tax string, start, count int) (posts []*Post, err error) { term, err := getTaxByName(tax, "category") if err != nil { if err == gorm.RecordNotFound { err = nil } return } // 写不出join语句,先一个个查吧... ids, err := getObjectsByTerm(term, start, count) if err != nil { if err == gorm.RecordNotFound { err = nil } return } for _, id := range ids { if post, err := getPostById(id.ObjectId, false); err == nil { posts = append(posts, post) } else { glog.Warn("getTopicsByTaxonomy: Not found post by id: %s tax: %s\n", id.ObjectId, tax) } } postSlice(posts).orderedBy("points", true) return }
// 查找一个主题的回复 func getReplyByPid(pid string, start, count int, options ...interface{}) (posts []*Post, err error) { q := db.Where("sub_type=?", "reply"). Where("post_parent=?", pid) if len(options) > 0 { opt := options[0].(map[string]interface{}) for key, val := range opt { switch key { case "points": sval := strings.ToLower(val.(string)) if sval != "desc" && sval != "asc" { glog.Warn("option for points invalid: %s, should be asc or desc.\n", sval) sval = "desc" } q = q.Order("points " + sval) } } } else { q = q.Order("floor asc") } err = q.Offset(start). Limit(count). Find(&posts).Error if err != nil && err != gorm.RecordNotFound { return } return }
// 更加不同的角度,查找posts // point: default, digest, rocket, latest, controversy func getPostsByPoint(point string, start, count int) (posts []*Post, ret int, err error) { q := db.Where("object_type=?", "post") switch point { case "default": q.Order("points desc") case "digest": q.Where("digest=1").Order("publish_at desc") case "latest": q.Order("post_at desc") case "rocket": // Todo case "controversy": // Todo default: glog.Warn("getPostsByPoint: unknown piont: %s\n", point) } err = q.Offset(start).Limit(count).Find(&posts).Error if err != gorm.RecordNotFound { err = nil } return }