案例:
查看陌陌的動態,依次可以按照發布時間,性別,城市進行篩選
如圖進行篩選
gorm鏈式操作
Method Chaining,Gorm 實現了鏈式操作接口,所以你可以把代碼寫成這樣:
// 創建一個查詢
tx := db.Where("name = ?", "jinzhu")
// 添加更多條件
if someCondition {
tx = tx.Where("age = ?", 20)
} else {
tx = tx.Where("age = ?", 30)
}
if yetAnotherCondition {
tx = tx.Where("active = ?", 1)
}
結合篩選動態的案例,代碼如下:
func (xy *Topic) GetTopicListByTimeGenderAddress(createTime, gender int, date, cityName string, adsID int64) (TopicList []Topic) {
//先創建一個查詢
tx := Db.Model(&xy).Where("ads_id = ? and status = 1", adsID)
//分類
if adsID > 0 {
tx = tx.Where("ads_id = ?", adsID)
}
//按照創建時間篩選
if createTime > 0 {
tx = tx.Order("create_time desc")
} else {
//按照活動時間篩選
tx = tx.Order("date_timestamp asc")
}
if gender > 0 {
tx = tx.Where("gender = ?", gender)
}
if cityName != "" {
tx = tx.Where("city_name = ?", cityName)
}
tx = tx.Preload("TopicImagesList")
tx.Find(&TopicList).RecordNotFound()
return TopicList
}